我有一段简单的代码,让我大吃一惊:
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 3.6.6,Ubuntu18.04,如果重要的话
发布于 2018-12-25 23:47:07
如果您注意到,从chr(10)开始保持不变,并通过断言测试。
所以真正的问题是,为什么chr(13)会被转换成chr(10)呢?为了回答这个问题,我们必须看看这些字符到底代表了什么。chr(13)是回车字符,而chr(10)是行提要字符。
您提到您正在使用Linux盒。Linux利用Unix模型,使用Line Feed字符,并且在其文件中不使用传输返回字符。因此,当将CR字符写入文件时,系统将其转换为系统使用的LF字符。然后,您正在读取文件(带有已翻译的字符),从而导致断言失败。
Here's是一篇很好的文章,介绍了不同的回报类型.
https://stackoverflow.com/questions/53926045
复制相似问题