Say, we are on Windows and we want to create a text file with the following content:
hello
world
We run
from pathlib import Path
Path('my.txt').write_text('hello\nworld')
and open the newly create my.txt
in an editor. I was expecting it to show LF
since we had \n
in our string (as opposed to \r\n
). To my surprise, my editor showed me that my.txt
had CRLF
.
Why did it happen? Is there a way to use write_text
to write LF
?
Python 3.10 (2021-10-04) now supports the newline
argument. So now you can do:
Path('my.txt').write_text('hello\nworld', newline='\n')
Reference:
Path.write_text(data, encoding=None, errors=None, newline=None)
https://docs.python.org/3/library/pathlib.html#pathlib.Path.write_text
Additional reference: