Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

newline

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.

like image 777
user1148478 Avatar asked Feb 07 '12 21:02

user1148478


People also ask

How do you write R and N in Python?

When you open the file for writing, just specify newline='\n' to ensure that it writes '\n' instead of the system default, which is \r\n on Windows.

How do you write to the next line in Python file handling?

Append Data to a New Line Using a New Line Character ( \n ) in Python. A new line is represented using a new line character or \n in programming languages such as Python or C++. While appending or adding new data to a file, we can add this character at the end of each line to add new data to a new line.

Does Python write add a new line?

In Python, the new line character “\n” is used to create a new line. When inserted in a string all the characters after the character are added to a new line. Essentially the occurrence of the “\n” indicates that the line ends here and the remaining characters would be displayed in a new line.


2 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.

like image 146
Praveen Gollakota Avatar answered Sep 21 '22 04:09

Praveen Gollakota


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.

like image 43
12431234123412341234123 Avatar answered Sep 23 '22 04:09

12431234123412341234123