2013-10-27 34 views
-1

非常基本的東西。我有一個文本文件,如:如何刪除逗號並將每個值放入新行?

0.34,0.35.... 

,我想刪除值之間的逗號,並把所有逗號分隔值到新行,需要這樣的:

0.34 
0.35 
+0

您是否考慮過搜索「python逗號分隔值」的信息?我懷疑這會證明是有益的。 :-) – DSM

+0

我試圖像:a.replace(',','\ n')但得到此錯誤: AttributeError:'列表'對象沒有屬性'替換' – Ibe

+0

好吧。我得到了: a.read()。replace(',','\ n') – Ibe

回答

0

這麼簡單,因爲它得到:

input_file = open('input.txt', 'r') 
output_file = open('output.txt', 'w') 

for value in input_file.readline().split(','): 
    output_file.write(value + '\n') 

input_file.close() 
output_file.close() 
+0

'打開(...):'是在Python中執行它的首選方法,因爲文件在出錯時關閉。 – Nils

0

該解決方案還可以刪除不必要的空格。

# convert 0.33, 0.34, 0.35 to 0.33\n0.34\n0.35 
# assume: The input file fits into one read() 

with open('input.txt', 'r') as i, open('output.txt', 'w') as o: 
    o.write(
     '\n'.join(
      [token.strip() for token in i.read().split(',')] 
     ) 
    )