When I try to run the following code.
string = ['A', 'B', '\r', '\n', 'C', 'D']
print(''.join(string))
import io
with io.open(r"test.txt", "w", encoding="utf-8-sig", newline='\r\n') as f:
f.write(''.join(string) "\r\n")
the output to terminal is
AB
CD
but the output to txt file (using notepad to check), it becomes \r\r\n
scr shot
how could I resolve it? (I don't want to change the input string
. I want to keep it as \r\n
)
I have tried to change the newlines, encoding. And search on google, however no luck.
CodePudding user response:
Reading the open
documentation about the newline
argument, it says:
When writing output to the stream, if newline is
None
, any'\n'
characters written are translated to the system default line separator,os.linesep
. If newline is''
or'\n'
, no translation takes place. If newline is any of the other legal values, any'\n'
characters written are translated to the given string.
[Emphasis mine]
By using newline='\r\n'
you have explicitly told the system to translate any single newline '\n'
into the carriage-return and newline pair '\r\n'
. If you also write an explicit carriage-return, then you will write two carriage-returns (one from the data you write, one from the newline translation).
Change to either newline=''
or newline='\n'
to not do any translations.