Search code examples
pythoncarriage-return

Python write a string to a file and keep \r


In python (2.7 or 3), say I have a string with \r in it, and I want to write it to a file and keep the \r. The default behavior is to replace the \r with \n. How can I do this? For example:

f= open("file.txt","w+")
f.write('foo\rbar')
f.close()

Leaves me with a file with text foo\nbar. I've read about universal newline handling, and I think I can use newline='' as an option for open() when opening a file with \r if I want to keep the \r. But write() does not accept the newline option, and I'm at a loss.

I have an application where the \r is meaningful, distinct from \n. And I need to be able to write to file and keep \r as it is.


Solution

  • Open the file in binary mode, appending a b to the mode you want to use.

    with open("file.txt","wb") as f:
        f.write(b'foo\rbar')
    

    It is better you use with open... instead of opening and closing the file by yourself.