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

发布于 2025-01-03 14:07:55 字数 348 浏览 2 评论 0原文

我有简单的代码:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

人疚 2025-01-10 14:07:55

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

以下是关于 open()

默认情况下使用文本模式,该模式可以在写入时将“\n”字符转换为特定于平台的表示形式,并在读取时将其转换回来。

You need to open the file in binary mode i.e. wb instead of w. 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().

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

你是暖光i 2025-01-10 14:07:55

您仍然可以使用文本模式,并且当您打印字符串时,您可以在打印之前删除最后一个字符,如下所示:

f.write("FooBar"[:-1])

使用 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:

f.write("FooBar"[:-1])

Tested with Python 3.4.2.

Edit: This does not work in Python 2.7.

胡大本事 2025-01-10 14:07:55

这是一个旧答案,但是 io.open 函数允许您指定行结尾:

import io
with io.open('tmpfile', 'w', newline='\r\n') as f:
    f.write(u'foo\nbar\nbaz\n')

来自:https ://stackoverflow.com/a/2642121/6271889

This is an old answer, but the io.open function lets you to specify the line endings:

import io
with io.open('tmpfile', 'w', newline='\r\n') as f:
    f.write(u'foo\nbar\nbaz\n')

From : https://stackoverflow.com/a/2642121/6271889

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文