Python逐行写入文本文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35685518/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python write line by line to a text file
提问by user2334436
I am trying to output the result from a Python script to a text file where each output should be saved to a line.
我试图将结果从 Python 脚本输出到文本文件,其中每个输出都应保存到一行。
f1=open('./output.txt', 'a')
f1.write(content + "\n")
When I open output.txt
with the regular notepad
the results look like this:
当我output.txt
使用常规打开时,notepad
结果如下所示:
color amber color aqua color analysis color app color adobe color alive app
However, when I open the file with notepad++
it looks fine and each word is saved on a line.
但是,当我用notepad++
它打开文件时看起来不错,并且每个单词都保存在一行中。
How can make the script save the result line-by-line so it would show the same on the regular notepad?
如何让脚本逐行保存结果,以便在常规记事本上显示相同的结果?
回答by AChampion
You may want to look into os dependent line separators, e.g.:
您可能需要查看依赖于操作系统的行分隔符,例如:
import os
with open('./output.txt', 'a') as f1:
f1.write(content + os.linesep)
回答by KeyWeeUsr
Well, the problem you have is wrong line ending/encoding for notepad. Notepad uses Windows' line endings - \r\n
and you use \n
.
好吧,您遇到的问题是记事本的行尾/编码错误。记事本使用 Windows 的行尾 -\r\n
而您使用\n
.