为什么在文本模式下编辑时不应该使用os.linesep?

Inf*_*ity 15 python

Python 2.7文档(以及Python 3文档)包含有关该os.linepath函数的以下行:

在编写以文本模式打开的文件时,不要将os.linesep用作行终止符(默认值);

这是为什么?它与在二进制模式下使用它有何不同?

And*_*ark 20

当您以文本模式打开文件时\n,您写入文件的任何内容都将转换为您正在使用的平台的相应行.

因此,举例来说,如果你是在Windows上哪里os.linesep'\r\n',当你写一个文件\n将获得自动转换为\r\n你将最终\r\r\n写入文件.

例如:

>>> import os
>>> os.linesep
'\r\n'
>>> with open('test.txt', 'w') as f:
...     f.write(os.linesep)
...
>>> with open('test.txt', 'rb') as f:
...     print repr(f.read())
...
'\r\r\n'
Run Code Online (Sandbox Code Playgroud)