Skip to content Skip to sidebar Skip to footer

Python 2.7 : How To Constrain The Delimiter Of A New Line To Be '\n' On Windows?

When I write into a text file within a python 2.7 script that runs on Windows the new line delimiter is '\r\n', but I would like it to be '\n'. I have tried to use open with newlin

Solution 1:

The following works for me and writes using \n instead of \r\n

 import io
 f= io.open("myfile.txt", "w", newline="\n")
 #note the io module requires you to write unicode
 f.write(unicode("asdasd\nasdasasd\n"))
 f.close()

Solution 2:

If you use open("file.ext", "wb") to open the file in binary mode, you will have your desired behavior. The conversion of "\n" to "\r\n" is only done:

  • if you're on Windows and
  • open your file in text mode, i.e. open("file.ext", "w")

Post a Comment for "Python 2.7 : How To Constrain The Delimiter Of A New Line To Be '\n' On Windows?"