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

huangapple go评论75阅读模式
英文:

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

问题

以下是您要翻译的内容:

我有以下在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正在使用它运行的系统的默认值这在大多数情况下都没问题然而在我的情况下我想要修复行尾样式无论在哪个系统上运行程序都一样

如何做到这一点
英文:

I have the following little program in 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)

After running it I get the following file (as expected)

line1
line2
line3

However, depending on where the program runs, line ending is different.

If I run it in Windows, I get CRLF line termination:

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

If I run it in Linux, I get LF line termination:

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

So, I understand that Python is using the default from the system in which it runs, which is fine most of the times. However, in my case I'd like to fix the line ending style, no matter the system where I run the program.

How this could be done?

答案1

得分: 1

可以使用newline参数来明确指定用于换行的字符串。它在open()pathlib.Path.open()中的使用方式相同。

下面的代码片段将始终使用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)

设置newline='\r\n'将使用Windows的换行符,不设置或设置为newline=None(默认值)将使用操作系统的默认换行符。

英文:

It is possible to explicitly specify the string used for newlines using the newline parameter. It works the same with open() and pathlib.Path.open().

The snippet below will always use Linux line endings \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)

Setting newline='\r\n' will give Windows line endings and not setting it or setting newline=None (the default) will use the OS default.

huangapple
  • 本文由 发表于 2023年6月1日 22:18:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/76382887.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定