1

I'm new to Python and I'm using one of the examples I found here to read lines from a file and print them. What I don't understand is why the interpreter ignores \n escape sequence:

Text file:

Which of the following are components you might find inside a PC? (Select all correct answers.)

A. CPU

B. Motherboard

C. Keyboard

Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM

Python code:

questions_fname="Test.txt"

with open(questions_fname, 'r') as f:
    questions = [line.strip() for line in f]

for line in questions:
    print (line)


f.close()

The result I get is strings like:

Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM

I was just looking for a simple way of formatting long lines to fit the screen.

2
  • Python automatically interprets a newline to be a '\n' character, you don't need to manually add them. Commented Jan 7, 2013 at 9:58
  • The escape sequences are interpreted only inside strings in the source file, not when reading data from a (text) file. Commented Jan 7, 2013 at 10:31

4 Answers 4

4

You don't have "\n" in the string, you have "\\n" since you're reading it from a file. If you want to have "\n" then you need to decode the string. Note that 3.x doesn't have str.decode(), so you can't use that mechanism from 2.x.

3>> codecs.getdecoder('unicode-escape')('foo\\nbar')[0]
'foo\nbar'
Sign up to request clarification or add additional context in comments.

3 Comments

+1 - completely forgot it was 3.x (was just looking at tags while typing!)
+1 -- there is nothing like automatically interpreted escape sequences in text files. The working newlines in the text file have always a binary form. You can .replace(r'\n', '\n') to get the wanted behaviour.
Note that if you're reading from a url in python 3 with urllib, then read() etc. return byte arrays, not strings. Conversion to strings with str() will result in '\\n in the string, but byte arrays do have a .decode() method, and using it will result in strings that are correctly formatted (i.e. that print new lines when passed to the print() function).
0

Try the following code to get the wanted behaviour...

questions_fname = "Test.txt"

with open(questions_fname) as f:
    for line in f:
        line = line.rstrip().replace('\\n', '\n')
        print(line)

The .rstrip() removes the trailing whitespaces, including the binary form of \n. The .replace() causes explicit, user defined interpretation of your \n sequences in the file content -- captured as the printable character \ followed by the n.

When using the with construct, the f.close() is done automatically.

Comments

0

\ is an escape character only in Python script, not in text files. When reading text files, Python converts all backslashes to \\, so when reading the file, \n becomes \\n which is not a newline character

Comments

-1

Sorry - this isn't valid for Python 3.x (I was looking at the tags), but I'll leave here as reference - please see @Ignacio's answer: https://stackoverflow.com/a/14193673/1252759

If you've effectively got a raw string that contains the literal characters '\n', then you can re-interpret the string to make it an escape sequence again:

>>> a = r"Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM"
>>> print a
Answers: A, B, and E. \nCommon components inside a PC include \nthe CPU,motherboard, and \nRAM
>>> print a.decode('string_escape')
Answers: A, B, and E. 
Common components inside a PC include 
the CPU,motherboard, and 
RAM

You may also want to look at the textwrap module if you want to wrap lines to a certain width for certain displays...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.