1

I'm saving a file containing \r with :

with open (filepath, mode = 'w') as file:
             file.write(content)

And I read it with :

with open (filepath, mode = 'r') as file:
             content = file.read()

I know that the characters \r are present in the saved file, but opening it with Python, they are replaced with \n.

So, how can I open my file with the \r ?

jorisb_
  • 13
  • 2

2 Answers2

2

By default python will translate the line endings to \n automatically when it reads a text file. Read this for a bit more info on line endings.

if you call open(filepath, mode='w', newline='') it should prevent python from translating those line endings.

mattrea6
  • 288
  • 1
  • 9
1

Open the file with rb instead of r (and wb instead of w) . This tells python to open in binary mode, and if you open without it (in text mode) python automatically normalizes end of line chars.

If you want to open in text mode, use the newline = '' parameter suggested in the other answers.

alon-k
  • 330
  • 2
  • 11