为什么要在不能使用Python的文本文件中写一个换行符?

lul*_*ulu 3 python newline text-files

我试图将列表保存到文本文件中,每个句子在一行上.但为什么这些代码对我不起作用?任何人?谢谢.

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()  
Run Code Online (Sandbox Code Playgroud)

Dee*_*ace 5

您正在为每个字符串打开文件text而不关闭它,这可能是导致您的错误的原因(您没有提及).

使用with并且不用担心关闭文件(也不要命名文件引用file,因为它会影响Python的内置文件).另请注意,您需要将其'a'用作打开模式,以便始终附加到文件而不是截断它:

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
Run Code Online (Sandbox Code Playgroud)

  • 即使OP关闭它也只会有一行,因为用写访问('w'`)打开将覆盖现有内容. (2认同)