tags:

views:

340

answers:

2

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.

+2  A: 

You'll need to use the binary pseudo-mode when opening the file.

f = open('file.txt', 'wb')
Jonathan Feinberg
+4  A: 

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.

Tamás