On windows, When using python to write a text file, how to change the file EOL from CRLF to LF?

On linux, the text file written by python uses LF (\n) as EOL by default. While on windows, the default EOL is CRLF(\r\n).

Set the EOL of python generated file

with open(file_path, 'w', newline='\n') as f:
    f.write(text)

The key point is newline='\n', it specifies the file EOL.

By default, open uses os.linesep as file EOL. On linux, os.linesep is \n. On windows, os.linesep is \r\n.

This article is originally created by tooli.top. Please indicate the source when reprinting : https://www.tooli.top/posts/python_file_newline

Posted on 2023-04-14 Mail to author