How can I force Python's file.write() to use the same newline format in Windows as in Linux ("rn" vs. "n")?
Question:
I have the simple code:
f = open('out.txt','w')
f.write('line1n')
f.write('line2')
f.close()
Code runs on windows and gives file size 12 bytes
, and linux gives 11 bytes
The reason is new line
In linux it’s n
and for win it is rn
But in my code I specify new line as n
. The question is how can I make python keep new line as n
always, and not check the operating system.
Answers:
You need to open the file in binary mode i.e. wb
instead of w
. If you don’t, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert ‘n’ characters to a platform-specific representation on writing and back on reading.
You can still use the textmode and when you print a string, you remove the last character before printing, like this:
f.write("FooBar"[:-1])
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
This is an old answer, but the io.open
function lets you to specify the line endings:
import io
with io.open('tmpfile', 'w', newline='rn') as f:
f.write(u'foonbarnbazn')
I have the simple code:
f = open('out.txt','w')
f.write('line1n')
f.write('line2')
f.close()
Code runs on windows and gives file size 12 bytes
, and linux gives 11 bytes
The reason is new line
In linux it’s n
and for win it is rn
But in my code I specify new line as n
. The question is how can I make python keep new line as n
always, and not check the operating system.
You need to open the file in binary mode i.e. wb
instead of w
. If you don’t, the end of line characters are auto-converted to OS specific ones.
Here is an excerpt from Python reference about open()
.
The default is to use text mode, which may convert ‘n’ characters to a platform-specific representation on writing and back on reading.
You can still use the textmode and when you print a string, you remove the last character before printing, like this:
f.write("FooBar"[:-1])
Tested with Python 3.4.2.
Edit: This does not work in Python 2.7.
This is an old answer, but the io.open
function lets you to specify the line endings:
import io
with io.open('tmpfile', 'w', newline='rn') as f:
f.write(u'foonbarnbazn')