How to write Unix end of line characters in Windows?

The modern way: use newline=””

Use the newline= keyword parameter to io.open() to use Unix-style LF end-of-line terminators:

import io
f = io.open('file.txt', 'w', newline="\n")

This works in Python 2.6+. In Python 3 you could also use the builtin open() function’s newline= parameter instead of io.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:

f = open('file.txt', 'wb')    # note the 'b' meaning binary

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”).

Leave a Comment