为什么多行字符串在打印或写入时会发生变化? (Python 3.6 在 Windows 上)

Why is multiline string altered on print or write? (Python 3.6 on Windows)

我在 Windows 上使用 Python 3.6.3。 当我尝试将单个多行字符串打印到文件时,如下所示:

with open('test1.txt', mode='w') as f:
    f.write('test\r\ntest\r\n')

然后 test1.txt 将最终包含 test\r\r\ntest\r\r\n 而不是 test\r\ntest\r\n

获得所需输出的解决方法如下所示:

with open('test2.txt', mode='w') as f:
    for line in 'test\r\ntest\r\n'.splitlines():
        print(line, file=f)

为什么会这样?

好吧,事实证明,正确地陈述一个问题通常会导致答案出现:

此行为的原因可在 TextIOWrapper 上的 Python 的 universal newline (quoting from PEP 3116 中找到:

On output, if newline is None, any '\n' characters written are translated to the system default line separator, os.linesep. If newline is '', no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string. (Note that the rules guiding translation are different for output than for input.)

这意味着,当打开文件进行写入时,可以将newline参数设置为''以获得所需的输出:

with open('test3.txt', mode='w', newline='') as f:
    f.write('test\r\ntest\r\n')