如何使用Python在Windows中编写Unix行尾字符

2024-04-26 08:05:09 发布

您现在位置:Python中文网/ 问答频道 /正文

如何使用Python(在Windows上)编写文件并使用Unix行尾字符?

例如,在执行以下操作时:

f = open('file.txt', 'w')
f.write('hello\n')
f.close()

Python会自动用\r\n替换


Tags: 文件txthelloclosewindowsunixopen字符
3条回答

现代方式:使用newline=''

使用newline=关键字参数来io.open()使用Unix样式的LF行结束符:

import io
f = io.open('file.txt', 'w', newline='\n')

这在Python2.6+中有效。在Python 3中,还可以使用内置的open()函数的newline=参数,而不是io.open()

旧方法:二进制模式

防止换行转换的旧方法(在Python 3中不起作用)是以二进制模式打开文件,以防止换行字符的转换:

f = open('file.txt', 'wb')    # note the 'b' meaning binary

但是在Python 3中,二进制模式将读取字节而不是字符所以它不会做您想要的事情。尝试在流上执行字符串I/O时,可能会出现异常。(例如,“TypeError:”str“不支持缓冲区接口”)。

打开文件时需要使用二进制伪模式。

f = open('file.txt', 'wb')

对于Python 2&3

请参阅本页上的The modern way: use newline=''答案。

仅适用于Python2(原始答案)

以二进制方式打开文件以防止行尾字符的转换:

f = open('file.txt', 'wb')

引用Python手册:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

相关问题 更多 >