我想在循环期间将字符串写入文件:
with open("dump.txt", "w+") as file:
for x in range(1, 10):
file.write(str(x) + "\r\n")
如果我在 Windows 上的记事本中打开
dump.txt
,我会得到我所期望的结果:
1
2
3
4
5
6
7
8
9
我必须在每行末尾添加
\r\n
,否则我会得到 123456789
(所有数字都在一行中)。
当我在 Notepad++ 中检查我的
dump.txt
时,我可以看到每行后都有一个额外的 CRLF:
1 CRLF
CRLF
2 CRLF
CRFL
etc.
当我将
dump.txt
读回 python 并循环遍历文件时,会输出额外的 LF:
import sys
with open("dump.txt", "r") as infile:
for line in infile:
sys.stdout.write(line)
C:\...\Python\Python38-32\python.exe C:/.../script.py
1
2
3
如果我在 Windows 上使用记事本创建一个新文件,然后输入数字 1 到 9,并在每行后按 Enter 键,Python 会正确读取它。在 Notepad++ 中我也没有看到任何额外的 CRLF 字符。
import sys
with open("dump2.txt", "r") as infile:
for line in infile:
sys.stdout.write(line)
C:\...\Python\Python38-32\python.exe C:/.../script2.py
1
2
3
...
9
我的问题是:我在这里缺少什么? Python 似乎为每个 file.write() 添加了第二个 CRLF,但前提是要写入的字符串已经以
"\r\n"
结尾。这是一种非常奇怪的行为。
我想逐行编写我的字符串,并以我明确的“结尾” " 或者使用脚本运行平台的 EOL 字符更好,就像我刚刚使用记事本手动创建了一个 txt 文件一样..
非常感谢您的帮助!
CRLF在Notepad++中的意思是“回车”,或者在Python中,它的意思是
\r
。如果您想在写入时删除它们,只需输入 \n
即可。
我遇到了同样的问题。
我是这样修复的
#string to write to a file
string_to_write = string_to_write.replace('\r\n','\r')
这对我来说很有效。
您应该在
open
命令中使用 定义要用作换行符的内容
newline='\n'
例如
with open("dump.txt", "w+", newline="\n") as file