I'm reading from a file which contains: this is the first line\\n this is the second line\\n\\nAnother line
I'm trying to read this file and keeping the special characters \\n
as they are.
with open(r'test.txt') as f:
c = f.read()
But printing c
shows always:
this is the first line\\\\n this is the second line\\\\n\\\\nAnother line
I've tried without prefixing with r
in r'text.txt'
but it doesn't change anything.
Is it possible to prevent escaping the special character \\n
?
I could do a str.replace('\\\\n','\\n')
of course, but I was just wondering whether we could do without this extra step.
I see 2 scenarios:
You are reading it on windows in text mode using Python 2. Windows is using \\r\\n
and Python 2 in text mode is thus expecting \\r\\n
. You should enable universal newline mode by adding U
, open('file.txt', 'rU')
. You can also use io.open
instead of open
. I don't have Python 2 so I haven't tried it...
You literally have two characters \\
and n
in your file and not a newline in which case everything is behaving as expected.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.