gpt4 book ai didi

python - 如何强制 Python 的 file.write() 在 Windows 中使用与 Linux ("\r\n"与 "\n"相同的换行符格式?

转载 作者:IT老高 更新时间:2023-10-28 20:22:13 26 4
gpt4 key购买 nike

我有简单的代码:

f = open('out.txt','w')
f.write('line1\n')
f.write('line2')
f.close()

代码在windows上运行并给出文件大小12字节,linux给出11字节原因是换行

在 linux 中是 \n 而对于 win 它是 \r\n

但在我的代码中,我将新行指定为 \n。问题是我怎样才能让 python 保持新行作为 \n 总是,而不是检查操作系统。

最佳答案

您需要以二进制模式打开文件,即wb而不是w。如果不这样做,行尾字符会自动转换为特定于操作系统的字符。

这是 Python 引用中关于 open() 的摘录。 .

The default is to use text mode, which may convert '\n' characters to a platform-specific representation on writing and back on reading.

关于python - 如何强制 Python 的 file.write() 在 Windows 中使用与 Linux ("\r\n"与 "\n"相同的换行符格式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9184107/

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