[python] 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')
f.write('line1\n')
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 \r\n

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.

This question is related to python newline

The answer is


You can still use the textmode and force the linefeed-newline 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.