user1148478 user1148478 - 2 years ago 62
Python Question

How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?

I have the simple code:

f = open('out.txt','w')

Code runs on windows and gives file size
12 bytes
, and linux gives
11 bytes

The reason is new line

In linux it's
and for win it is

But in my code I specify new line as
. The question is how can I make python keep new line as
always, and not check the operating system.

Answer Source

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.

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