英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论