编写文本文件时,如何在 Python 中修复行尾样式(CRLF 或 LF)?

How to fix the line ending style (either CRLF or LF) in Python when written a text file?

提问人:fgalan 提问时间:6/1/2023 更新时间:6/1/2023 访问量:223

问:

我在 Python 中有以下小程序

from pathlib import Path
filename = Path("file.txt")
content = "line1\nline2\nline3\n"
with filename.open("w+", encoding="utf-8") as file:
    file.write(content)

运行它后,我得到以下文件(如预期)

line1
line2
line3

但是,根据程序的运行位置,行尾会有所不同。

如果我在 Windows 中运行它,我会得到 CRLF 线路终止:

$ file -k file.txt
file.txt: ASCII text, with CRLF line terminators

如果我在 Linux 中运行它,我会得到 LF 线路终止:

$ file -k file.txt 
file.txt: ASCII text

所以,我知道 Python 正在使用它运行的系统中的默认值,这在大多数时候都很好。但是,就我而言,无论我在哪个系统运行程序,我都想修复行尾样式。

这是怎么做到的?

python 行尾

评论


答:

1赞 Friedrich 6/1/2023 #1

可以使用参数显式指定用于换行符的字符串。它与 open()pathlib 的工作方式相同。路径.open()。newline

下面的代码片段将始终使用 Linux 行尾:\n

from pathlib import Path
filename = Path("file.txt")
content = "line1\nline2\nline3\n"
with filename.open("w+", encoding="utf-8", newline='\n') as file:
    file.write(content)

设置将给出 Windows 行结尾,不设置它或设置(默认)将使用操作系统默认值。newline='\r\n'newline=None