gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 17:16:40 25 4
gpt4 key购买 nike

Python 2.7 documentation (以及 Python 3 documentation)包含以下关于 os.linepath 函数的行:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default);

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

最佳答案

当您以文本模式打开文件时,您写入文件的任何 \n 都会转换为适合您所用平台的行尾。

因此,例如,如果您在 os.linesep'\r\n' 的 Windows 上,当您将其写入文件时,\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'

关于python - 为什么在文本模式下编辑时不应该使用 os.linesep?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21636213/

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