找到你要的答案

Q:Why is writing a newline to a text file not working in Python?

Q:为什么写一行到一个文本文件不使用Python?

I am trying to save the lists into the text file which each sentence on one line. But why are these codes not working for me? Anyone? Thank you.

import codecs

text = ["good morning", "hello everybody"] 

for texts in text:
    file = codecs.open("newlinetest.txt", "w", "utf-8")
    print texts
    file.write(texts + "\n")

file.close()  

我试着把列表保存到一行的每个句子的文本文件中。但是为什么这些代码不适合我呢?有人吗?谢谢您.

import codecs

text = ["good morning", "hello everybody"] 

for texts in text:
    file = codecs.open("newlinetest.txt", "w", "utf-8")
    print texts
    file.write(texts + "\n")

file.close()  
answer1: 回答1:

You are opening the file for each string in text without closing it, which is probably what causes your error (which you didn't mention).

Use with and don't bother with closing the file (and also don't name the file reference file, as it will shadow Python's built-in file). Also note that you will need to use 'a' as the opening mode so you always appending to the file instead of truncating it:

import codecs

text = ["good morning", "hello everybody"] 

with codecs.open("newlinetest.txt", "a", "utf-8") as my_file:  # better not shadow Python's built-in file
    for texts in text:
         print texts
         my_file.write(texts + "\n")
# no need to call my_file.close() at all

您正在打开文本中的每个字符串的文件,而不关闭它,这可能是什么原因导致您的错误(您没有提到)。

用不必关闭文件(也没有名字的文件参考文件,因为它将影子Python的内置文件)。也请注意,您将需要使用一个“开放的模式,所以你总是附加而不是截断它的文件:

import codecs

text = ["good morning", "hello everybody"] 

with codecs.open("newlinetest.txt", "a", "utf-8") as my_file:  # better not shadow Python's built-in file
    for texts in text:
         print texts
         my_file.write(texts + "\n")
# no need to call my_file.close() at all
answer2: 回答2:

You just need to open the file once outside the loop and you can use str.join to write, w overwrites so you are overwriting each iteration ending up with only the last element from the list written:

import codecs

text = ["good morning", "hello everybody"]
with codecs.open("newlinetest.txt", "w", "utf-8") as f:
    f.write("\n".join(text))

Since you are passing a list, the csv module would be a good fit for what you want to do using a newline as the delimiter:

text = ["good morning", "hello everybody"]
import csv
with codecs.open("newlinetest.txt", "w", "utf-8") as f:
    wr = csv.writer(f,delimiter="\n")
    wr.writerow(text)

你只需要打开文件一旦外环,你可以用str.join写,W覆盖你覆盖每个迭代结束了只有从名单上写的最后一个元素:

import codecs

text = ["good morning", "hello everybody"]
with codecs.open("newlinetest.txt", "w", "utf-8") as f:
    f.write("\n".join(text))

当你传递一个列表,csv模块将你想要使用一个换行符作为分隔符,一个不错的选择:

text = ["good morning", "hello everybody"]
import csv
with codecs.open("newlinetest.txt", "w", "utf-8") as f:
    wr = csv.writer(f,delimiter="\n")
    wr.writerow(text)
python  text-files  newline