python 2 和 python 3 之间的 read() 差异

read() differences between python 2 and python 3

具有以下 MWE:

with open('a','w') as f:
    f.write('\r')
with open('a','r') as f:
    print(ord(f.read()))

我得到以下输出:

$ python2 test.py 
13
$ python3 test.py 
10

你能解释一下为什么吗?据我所知,13 是 ascii 和 UTF-8 中 \r 的预期十进制数。

Python 3's open defaults to universal newlines mode (newline=None), while Python 2's open 仅在模式字符串包含 U.

时启用通用换行模式

在通用换行模式下,序列\r(旧Mac)、\n(UNIX)或\r\n(DOS/Windows)都被识别作为换行符,并自动转换为 \n 因此行尾具有一致的表示形式以简化字符串操作。

如果你想要 Python 2 中的通用换行符,你可以使用模式字符串来启用它或 use io.open,这几乎完全等同于 Python 3 的 built-in open(Python 3 上的 io.open 只是 open 的另一种说法)。

如果您想在 Python 3 上禁用通用换行符处理,请向 open 传递一个 newline='' 的参数(用于在 [=41= 时换行的通用识别) ],但没有行尾的翻译)或 newline='\n'(例如)表示只有 \n 被识别为行尾,同样,不执行行尾的翻译。需要传递 newline='' 才能正确处理某些文件格式; csv 模块执行自己的行结束处理,newline='' 确保在到达 csv reader.

之前没有信息丢失