gpt4 book ai didi

python - 将 chr(13) 写入文件时读取时会给出 chr(10)

转载 作者:行者123 更新时间:2023-11-30 22:01:50 40 4
gpt4 key购买 nike

一段简单的代码让我大吃一惊:

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) 是回车符,而 chr(10) 是换行符。

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

Here's关于返回类型差异的好文章。

关于python - 将 chr(13) 写入文件时读取时会给出 chr(10),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53926045/

40 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com