python - os.linesep 是干什么用的?

标签 python file-io separator platform-independent

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已经探讨了为什么您不应该在这种情况下使用它,但是它对什么情况有用?什么时候应该使用行分隔符?用于什么目的?

最佳答案

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

不完全是。文档说不要在 text 模式下使用它。

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 - os.linesep 是干什么用的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38074811/

相关文章:

java - 如何读取Maven应用程序的webapp文件夹中的目录

java - 是否有任何用于二进制文件解析的 Java 框架?

xcode - 如何在 iOS 14 中删除 SwiftUI 2.0 中的列表分隔符行

android - 如何在以编程方式创建的 TableRows 之间添加分隔线?

python - 如何统计文件中的句子、单词和字符的数量?

python - 使用 gdal 将数组转换为 tiff 光栅图像

c++ - 使用频率和行出现的文本文件标记化。使用 C++

python - 在 Python input() 函数中插入分隔符

python - 括号 URL 调度程序 Django?

Python 从 C 运行 main python multiprocess