Search code examples
pythonfiletextnewlinestrip

Python changes \n to \\n when reading a text file


I have a text file that contains \n as new line in it.

In Python 3.6, when I load it using the following code:

file = open(file_name, 'r')
contents = file.read()

it changes all \n to \\n. For example:

Original in the txt file:

This is a test \n plus senond \n test.

After reading in Python:

"This is a test \\n plus senond \\n test."

I need to keep all the \n to work as new line and do much more analysis on them (using reg ex).

What is the correct method to read the file and solve this issue?


Solution

  • All actual newline characters (linefeed / LF, hex value 0x0A) are preserved by default when reading a file in Python. But your file seems to contain escape sequences, which you want to convert to actual, single newline characters.

    In this case, just use: print(contents.replace("\\n", "\n"))