How to write Unix line ending characters on Windows using Python

How can I write files using Python (on Windows) and use the Unix line ending character?

eg. While doing:

 f = open ('file.txt', 'w')
 f.write ('hello \ n')
 f.close ()

Python automatically replaces \ n with \ r \ n.

+50
python newline
Mar 29 '10 at 8:17
source share
3 answers

For Python 2 and 3

See: The modern way: use the answer newline = `` on this page itself.

Python 2 only (original answer)

Open the file as binary to prevent trailing characters:

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

Python manual tip:

On Windows, the 'b' added to mode opens the file in binary mode, so there are also modes such as "rb", "wb" and "r + b". Python on Windows makes a distinction between text and binary; trailing characters in text files are automatically changed when data is read or written. This behind-the-scenes file data modification is great for ASCII text files, but they corrupt binary data like those 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 add β€œb” to mode, so you can use its platform independently for all binary files.

+51
Mar 29 '10 at 8:19
source share

Modern way: use newline = ''

Use the newline= keyword parameter for io.open () to use Unix-style end-line end-terminals:

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

This works in Python 2.6+. In Python 3, you can also use the built-in parameter open() function newline= instead of io.open() .

Old way: binary mode

The old way to prevent newline conversion that doesn't work in Python 3 is to open the file in binary mode to prevent trailing characters:

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

but in Python 3, binary mode will read bytes, not characters, so it won’t do what you want. You will probably get exceptions when you try to perform string I / O on a thread. (for example, "TypeError:" str "does not support the buffer interface").

+54
May 2 '14 at 18:25
source share

When opening a file, you will need to use binary pseudo-mode.

 f = open('file.txt', 'wb') 
+7
Mar 29 '10 at 8:19
source share



All Articles