How can I make Python file.write () use the same newline format on Windows as on Linux ("\ r \ n" versus "\ n")?

I have a simple code:

f = open('out.txt','w') f.write('line1\n') f.write('line2') f.close() 

The code works in windows and gives a file size of 12 bytes , and linux gives 11 bytes The reason is a new line

On linux, it's \n , and for win, it's \r\n

But in my code, I am specifying a new line as \n . The question is, how can I get python to support the new line as \n always, and not check the operating system.

+57
python newline
Feb 07 2018-12-21T00:
source share
2 answers

You need to open the file in binary mode, i.e. wb instead of w . If you do not, the line breaks are automatically converted to OS-specific.

Here is an excerpt from Python help on open() .

By default, text mode is used, which can convert the characters "\ n" to a platform-specific representation when writing and reading back.

+89
Feb 07 2018-12-21T00:
source share

You can still use text mode and force the use of line-to-line string with the keyword argument newline

 f = open("./foo",'w',newline='\n') 

Tested with Python 3.4.2.

Edit: This does not work in Python 2.7.

+9
Jun 08 '16 at 15:13
source share



All Articles