Reputation: 197
I have a text file which contains \n (back-slash N) in the file's contents. I want Python to interpret \n as a new line, rather than a literal \n string.
samplefile.txt contains
multi\nline
My Python code
file_path = "./samplefile.txt"
with open(file_path, "r") as f:
contents = f.read()
print(contents)
The print statement currently outputs this:
multi\nline
But I want it to output this:
multi
line
After I read the file's contents, how can I get Python to interpret \n in the file's contents as a new line?
What I've tried:
contents = repr(contents).replace("\\n", "\n")
print(contents)
But that outputs:
'multi\
line
'
Expected output:
multi
line
Any suggestions?
Upvotes: 1
Views: 803