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)
您正在为每个字符串打开文件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)
| 归档时间: |
|
| 查看次数: |
3832 次 |
| 最近记录: |