os.linesep是干什么的?

2024-06-26 02:47:48 发布

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

Python的os模块包含一个特定于平台的行分隔字符串的值,但是文档明确表示在写入文件时不要使用它:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Docs

Previous questions已经探索了为什么不应该在这个上下文中使用它,但是它对什么上下文有用?你应该什么时候使用行分隔符,做什么?


Tags: 模块文件字符串文档osuseasline
2条回答

the docs explicitly say not to use it when writing to a file

这不准确,文档说不要在文本模式下使用它。

当您想遍历文本文件的行时,使用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”字符都转换为系统默认的行分隔符:“\r\n”在Windows上,“\n”在POSIX上,等等

使用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')显式转换行尾。如果文件(或流或其他)包含二进制和文本数据的组合,则这可能很有用。

相关问题 更多 >