如何强制 Python 的 file.write() 在 Windows 中使用与 Linux 中相同的换行格式(“\r\n”与“\n”)?
我有简单的代码:
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
,而不检查操作系统。
I have the simple code:
f = open('out.txt','w')
f.write('line1\n')
f.write('line2')
f.close()
Code runs on windows and gives file size 12 bytes
, and linux gives 11 bytes
The reason is new line
In linux it's \n
and for win it is \r\n
But in my code I specify new line as \n
. The question is how can I make python keep new line as \n
always, and not check the operating system.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要以二进制模式打开文件,即
wb
而不是w
。如果不这样做,行尾字符将自动转换为操作系统特定的字符。以下是关于
open()
。You need to open the file in binary mode i.e.
wb
instead ofw
. If you don't, the end of line characters are auto-converted to OS specific ones.Here is an excerpt from Python reference about
open()
.您仍然可以使用文本模式,并且当您打印字符串时,您可以在打印之前删除最后一个字符,如下所示:
使用 Python 3.4.2 进行测试。
编辑:这在 Python 2.7 中不起作用。
You can still use the textmode and when you print a string, you remove the last character before printing, like this:
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
这是一个旧答案,但是 io.open 函数允许您指定行结尾:
来自:https ://stackoverflow.com/a/2642121/6271889
This is an old answer, but the
io.open
function lets you to specify the line endings:From : https://stackoverflow.com/a/2642121/6271889