Python 的 os 模块包含一个平台特定行分隔字符串的值,但文档明确表示在写入文件时不要使用它:
写入以文本模式打开的文件时,不要使用 os.linesep 作为行终止符(默认);在所有平台上使用单个 '\n'。
之前的问题已经探讨了为什么你不应该在这种情况下使用它,但是它对什么情况有用呢?什么时候应该使用行分隔符,为了什么?
文档明确说在写入文件时不要使用它
这不准确,文档说不要在文本模式下使用它。
当os.linesep
您想要遍历文本文件的行时使用。内部扫描仪识别os.linesep
并用单个“\n”替换它。
为了说明,我们编写了一个二进制文件,其中包含由“\r\n”(Windows 分隔符)分隔的 3 行:
import io
filename = "text.txt"
content = b'line1\r\nline2\r\nline3'
with io.open(filename, mode="wb") as fd:
fd.write(content)
二进制文件的内容是:
with io.open(filename, mode="rb") as fd:
for line in fd:
print(repr(line))
注意:我使用“rb”模式将文件作为二进制文件读取。
我得到:
b'line1\r\n'
b'line2\r\n'
b'line3'
如果我使用文本模式读取文件的内容,如下所示:
with io.open(filename, mode="r", encoding="ascii") as fd:
for line in fd:
print(repr(line))
我得到:
'line1\n'
'line2\n'
'line3'
分隔符替换为“\n”。
也用于写入模式:任何“ os.linesep
\n”字符都将转换为系统默认的行分隔符:Windows 上的“\r\n”,POSIX 上的“\n”等。
使用该io.open
功能,您可以将行分隔符强制为您想要的任何内容。
示例:如何编写 Windows 文本文件:
with io.open(filename, mode="w", encoding="ascii", newline="\r\n") as fd:
fd.write("one\ntwo\nthree\n")
如果您以这样的文本模式阅读此文件:
with io.open(filename, mode="rb") as fd:
content = fd.read()
print(repr(content))
你得到:
b'one\r\ntwo\r\nthree\r\n'
如您所知,在 python 中以文本模式读取和写入文件会将特定于平台的行分隔符转换为 '\n',反之亦然。但是,如果您以二进制模式读取文件,则不会发生转换。然后,您可以使用string.replace(os.linesep, '\n')
. 如果文件(或流或其他)包含二进制和文本数据的组合,这将很有用。