1

I need to write to a file some text while contains a mix of line breaks \r and \n, and I want to keep both. However, in python 3 when I write this text to the file, all instances of \r are replaced with \n. This behavior is different from python 2, as you can see in the output below. What can I do to stop this replacement?

Here is the code:

import string
printable=string.printable
print([printable])
fopen=open("test.txt","w")
fopen.write(printable)
fopen.close()

fopen=open("test.txt","r")
content=fopen.read()
print([content])
fopen.close()

and here is the output, when I run the code on python 2 and python 3:

(base) Husseins-Air:Documents hmghaly$ python2.7 test_write_line_break.py 
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c']
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c']
(base) Husseins-Air:Documents hmghaly$ python test_write_line_break.py 
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c']
['0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\n\x0b\x0c']
hmghaly
  • 1,411
  • 3
  • 29
  • 47
  • 2
    Does this answer your question? [How can I force Python's file.write() to use the same newline format in Windows as in Linux ("\r\n" vs. "\n")?](https://stackoverflow.com/questions/9184107/how-can-i-force-pythons-file-write-to-use-the-same-newline-format-in-windows) – BeneSim Apr 12 '20 at 12:03
  • 1
    Does this answer your question? https://stackoverflow.com/questions/17391437/how-to-use-r-to-print-on-same-line – Farhood ET Apr 12 '20 at 12:05
  • 1
    The behavior you describe is exactly according to the [documentation](https://docs.python.org/3/library/functions.html#open), which also mentions how to change this behavior. – wovano Apr 12 '20 at 12:10

1 Answers1

5

The issue is a python feature known as 'univeral newlines' that translates any types of line breaks in the source file to whatever the line seperator is in the output. You can disable this behavior with newline='' in the open function:

fopen=open("test.txt", "w", newline='')
...
fopen=open("test.txt", "r", newline='')
mousetail
  • 7,009
  • 4
  • 25
  • 45