tttppp tttppp - 1 year ago 115
Python Question

How to write Unix end of line characters in Windows using Python

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')

Python automatically replaces \n with \r\n.

Answer Source

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:

f = open('file.txt', 'wb')

Quoting the Python manual:

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download