如何用Python在文件中写入新行
我有一个这样的文件:如何用Python在文件中写入新行,python,file,optimization,split,newline,Python,File,Optimization,Split,Newline,我有一个这样的文件: word, number word, number [...] 我只想保留这些词,还是新行中的一个词 word word [...] 到目前为止我的代码 f = open("new_file.txt", "w") with open("initial_file.txt" , "r+") as l: for line in l: word = line.split(", ")[0] f.write(word) print word # debugg
word, number
word, number
[...]
我只想保留这些词,还是新行中的一个词
word
word
[...]
到目前为止我的代码
f = open("new_file.txt", "w")
with open("initial_file.txt" , "r+") as l:
for line in l:
word = line.split(", ")[0]
f.write(word)
print word # debugging purposes
给我新文件中一行中的所有单词
wordwordwordword[...]
哪一种是最适合做这件事的pythonic和最优化的方法?
我试图使用f.write(“\n.join(word))
,但我得到的是
wordw
ordw
[...]
只需使用
f.write(str(word)+“\n”)
即可。此处str
用于确保我们可以添加“\n”
如果您在Windows上,最好使用“\r\n”