73

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.

Daniel F
  • 13,684
  • 11
  • 87
  • 116
user1148478
  • 741
  • 1
  • 6
  • 4

3 Answers3

106

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.

Praveen Gollakota
  • 37,112
  • 11
  • 62
  • 61
  • 10
    In Python 3, since strings are not encoded, you will need to write them with something like `outfile.write(bytes(line, "UTF-8"))` to avoid a `TypeError: 'str' does not support the buffer interface`. – Noumenon Oct 12 '17 at 16:00
  • 4
    You do not _need_ to open the file in binary mode, it is one way to solve it but not the only one – 12431234123412341234123 Dec 09 '20 at 09:22
27

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.

  • 1
    I've defined the `newline` as suggested, but the `f.write()` commands don't automatically insert this between writes. How to do that? – Nikhil VJ Apr 15 '18 at 04:25
  • 1
    @nikhilvj. Please read the corresponding documentation: `write()` do not insert newlines. – 12431234123412341234123 Apr 16 '18 at 13:37
  • 2
    ok my bad. If it helps, I found that once `newline='\r\n'` or anything is specified in the open() command, we don't need to worry about putting the 'right' newline in the `write()` commands. We just need to say `\n` and that will get replaced with the custom newline string we have configured. – Nikhil VJ Apr 16 '18 at 18:44
7

This is an old answer, but the io.open function lets you to specify the line endings:

import io
with io.open('tmpfile', 'w', newline='\r\n') as f:
    f.write(u'foo\nbar\nbaz\n')

From : https://stackoverflow.com/a/2642121/6271889

Leonardo
  • 1,533
  • 17
  • 28
  • 4
    As the [documentation](https://docs.python.org/3/library/io.html#io.open) states, the function `io.open` is just an alias for the built-in function [`open`](https://docs.python.org/3/library/functions.html#open). There is no difference between them. – Jeyekomon Jul 15 '21 at 13:27