jorisb_
jorisb_

Reputation: 13

Save and read `\r` in a file - Python 3

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 ?

Upvotes: 1

Views: 774

Answers (2)

alon-k
alon-k

Reputation: 438

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.

Upvotes: 2

mattrea6
mattrea6

Reputation: 338

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.

Upvotes: 3

Related Questions