将 chr(13) 写入文件在读取时给出 chr(10)

writing chr(13) to file gives chr(10) when read

我有一段简单的代码让我心碎:

if __name__ == '__main__':
    writen_text = chr(13)
    file = open('bug', 'w')
    file.write(writen_text)
    file.close()
    file = open('bug')
    read_text = ''.join(file.readlines())
    print([ord(c) for c in writen_text])
    print([ord(c) for c in read_text])
    assert writen_text == read_text

输出为

[13]
[10]
Traceback (most recent call last):
  File "/bug.py", line 10, in <module>
    assert writen_text == read_text
AssertionError

这是什么???我只想将文本写入文件并在不做任何更改的情况下准确读取该文本

Python3.6.6,Ubuntu18.04,如果有关系

如果您注意到,从 chr(10) 开始保持不变并通过您的断言测试。

所以真正的问题是为什么 chr(13) 会变成 chr(10)?为了回答这个问题,我们必须看看这些字符中的每一个实际上代表什么。 chr(13) 是回车 return 字符,而 chr(10) 是换行符。

您提到您正在使用 Linux 盒子。 Linux,利用 Unix 模型,在其文件中使用换行符而不使用回车符 Return 字符。因此,当将 CR 字符写入文件时,系统将其转换为系统使用的 LF 字符。然后,您正在读取文件(带有翻译后的字符),因此断言失败。

Here's 关于 return 类型差异的好文章 post。