简体   繁体   English

为什么 \r\n output 变成 \r\r\n 使用 python 写入文件

[英]Why \r\n output become \r\r\n using python write to file

When I try to run the following code.当我尝试运行以下代码时。

string = ['A', 'B', '\r', '\n', 'C', 'D']
print(''.join(string))
import io
with io.open(r"test.txt", "w", encoding="utf-8-sig", newline='\r\n') as f:
    f.write(''.join(string)+"\r\n")

the output to terminal is到终端的 output 是

AB
CD

but the output to txt file (using notepad++ to check), it becomes \r\r\n scr shot但是把output转成txt文件(用notepad++查看),变成了\r\r\n scr shot

how could I resolve it?我该如何解决? (I don't want to change the input string . I want to keep it as \r\n ) (我不想更改输入string 。我想将其保留为\r\n

I have tried to change the newlines, encoding.我试图改变换行符,编码。 And search on google, however no luck.并在谷歌上搜索,但没有运气。

Reading the open documentation about the newline argument, it says:阅读有关newline参数open文档,它说:

When writing output to the stream, if newline is None , any '\n' characters written are translated to the system default line separator, os.linesep .将 output 写入 stream 时,如果换行符None ,则写入的任何'\n'字符都将转换为系统默认行分隔符os.linesep If newline is '' or '\n' , no translation takes place.如果换行符'''\n' ,则不会进行任何翻译。 If newline is any of the other legal values, any '\n' characters written are translated to the given string.如果换行符是任何其他合法值,则写入的任何'\n'字符都将转换为给定的字符串。

[Emphasis mine] [强调我的]

By using newline='\r\n' you have explicitly told the system to translate any single newline '\n' into the carriage-return and newline pair '\r\n' .通过使用newline='\r\n'您已明确告诉系统将任何单个换行符'\n'转换为回车符和换行符对'\r\n' If you also write an explicit carriage-return, then you will write two carriage-returns (one from the data you write, one from the newline translation).如果你还写了一个明确的回车,那么你将写两个回车(一个来自你写的数据,一个来自换行翻译)。

Change to either newline='' or newline='\n' to not do any translations.更改为newline=''newline='\n'以不进行任何翻译。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM