Python 将字符串写入文件并保留 \r

Python write a string to a file and keep \r

在 python(2.7 或 3)中,假设我有一个包含 \r 的字符串,我想将它写入文件并 keep \r。默认行为是用 \n 替换 \r。我怎样才能做到这一点?例如:

f= open("file.txt","w+")
f.write('foo\rbar')
f.close()

给我留下一个文本为 foo\nbar 的文件。我已经阅读了有关通用换行符处理的信息,我想我可以在使用 \r 打开文件时使用 newline='' 作为 open() 的选项,如果我想保留 \r .但是write()不接受newline选项,我很茫然

我有一个应用程序,其中 \r 是有意义的,不同于 \n。我需要能够写入文件并保持 \r 原样。

以二进制模式打开文件,在您要使用的模式后附加 b

with open("file.txt","wb") as f:
    f.write(b'foo\rbar')

最好使用with open...而不是自己打开和关闭文件。

以二进制格式读写。

f= open("file.txt","wb")
f.write(b'foo\rbar')
f.close()

显然每个人都有自己的喜好。

我将在您的代码中添加一个 r 以使该字符串成为原始字符串:

f= open("file.txt","w+")
f.write(r'foo\rbar') # right before the string
f.close()

你很高兴。

您可以使用 newline='' 打开文件,以便在输出时不进行任何翻译。 write 方法没有 newline 参数,因为文件对象已经用它初始化:

with open('file.txt', 'w', newline='') as f:
    f.write('foo\rbar')

摘自documentation

When writing output to the stream, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '' or '\n', no translation takes place.