garlic
garlic

Reputation: 197

Interpret \n as new line when text file contains \n in the text

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

Answers (1)

john-hen
john-hen

Reputation: 4866

In the code you tried, just drop the call to repr(). It escapes the backslash, which is not what you want. So it's just this:

>>> content = r'multi\nline'
>>> print(content.replace("\\n", "\n"))
multi
line

Upvotes: 3

Related Questions