如何在 Python 中的文件中写入新行

How to write in new line in file in Python

我有一个这样的文件:

word, number
word, number
[...]

我想 take/keep 只是单词,在新行中又是一个单词

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"