How can I write to files using Python (on Windows) and use the Unix end of line character?
e.g. When doing:
f = open('file.txt', 'w') f.write('hello\n') f.close()
Python automatically replaces \n with \r\n.
How can I write to files using Python (on Windows) and use the Unix end of line character?
e.g. When doing:
f = open('file.txt', 'w') f.write('hello\n') f.close()
Python automatically replaces \n with \r\n.
You'll need to use the binary pseudo-mode when opening the file.
For Python 2 & 3
See: The modern way: use newline='' answer on this very page.
For Python 2 only (original answer)
Open the file as binary to prevent the translation of end-of-line characters:
Quoting the Python manual:
The modern way: use newline=''
Use the
newline=
keyword parameter to io.open() to use Unix-style LF end-of-line terminators:This works in Python 2.6+. In Python 3 you could also use the builtin
open()
function'snewline=
parameter instead ofio.open()
.The old way: binary mode
The old way to prevent newline conversion, which does not work in Python 3, is to open the file in binary mode to prevent the translation of end-of-line characters:
but in Python 3, binary mode will read bytes and not characters so it won't do what you want. You'll probably get exceptions when you try to do string I/O on the stream. (e.g. "TypeError: 'str' does not support the buffer interface").