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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With