来自文本文件的新行

时间:2013-04-08 21:10:05

标签: python

我有一个这种格式的文件example.txt:

a,b,c,d

我希望将其转换为:

a
b
c
d

我写了这个,但它不起作用:

with open('newline.txt', 'w') as f: 
    f.write (file("example.txt", "r").read().replace(",", "\n"))

2 个答案:

答案 0 :(得分:1)

你也可以这样做:

with open('newline.txt', 'w') as f:  
    f.writelines (w + '\n' for w in open("example.txt").read().split(","))

答案 1 :(得分:0)

它应该是:

with open('newline.txt', 'w') as f: 
    f.write (open("example.txt", "r").read().replace(",", "\n"))

documentary中声明,在打开文件时,最好使用open()而不是直接调用file()构造函数