Reputation: 368
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.
Upvotes: 5
Views: 3659
Reputation: 106445
You can open the file with newline=''
so that on output, no translation takes place. The write
method does not have a newline
parameter because the file object is already initialized with it:
with open('file.txt', 'w', newline='') as f:
f.write('foo\rbar')
Excerpt from the documentation:
When writing output to the stream, if
newline
isNone
, any'\n'
characters written are translated to the system default line separator,os.linesep
. Ifnewline
is''
or'\n'
, no translation takes place.
Upvotes: 0
Reputation: 69705
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.
Upvotes: 4
Reputation: 2982
Everyone has their preferences apparently.
I'm just going to add an r
to your code to make the string a raw string:
f= open("file.txt","w+")
f.write(r'foo\rbar') # right before the string
f.close()
And you are good to go.
Upvotes: -1
Reputation: 1585
read and write in binary format.
f= open("file.txt","wb")
f.write(b'foo\rbar')
f.close()
Upvotes: 0