Search code examples
pythonline-endings

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


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?


Solution

  • 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.