【问题标题】:How to write in new line in file in Python如何在 Python 中的文件中写入新行
【发布时间】:2015-05-24 20:31:18
【问题描述】:

我有一个文件是这样的:

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
[...]

【问题讨论】:

    标签: python file optimization split newline


    【解决方案1】:

    您可以使用f.write(str(word)+"\n") 来执行此操作。这里str用来确保我们可以添加“\n”。

    如果您使用的是 Windows,最好使用 "\r\n"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-27
      • 2012-07-14
      相关资源
      最近更新 更多