Reading newlines from a text file

Peter Otten __peter__ at web.de
Sat Feb 28 14:55:16 EST 2004


Thomas Philips wrote:

> I have a data file that I read with readline(), and would like to
> control the formats of the lines when they are printed. I have tried
> inserting escape sequences into the data file, but am having trouble
> getting them to work as I think they should. For example, if my data
> file has only one line which reads:
> 1\n234\n567
> 
> I would like to read it with a command of the form
> x=datafile.readline()
> 
> and I would like
> print x
> 
> to give me
> 1
> 234
> 567
> 
> The readline works like a charm, but the print gives me
> 1\n234\n567
> Clearly the linefeeds are not interpreted as such. How can I get the
> Python interpreter to correctly interpret escape sequences in strings
> that are read from files?

I see you are using "correct" as a synonym for "the way I want" :-)
The Python interpreter does not interpret data read from a file and you were
in for serious trouble if it would. However, you can process the data in
any way you like, and here's how to replace C-style escape sequences with
the corresponding characters:

>>> import codecs
>>> file("tmp.txt", "w").write("\\ntoerichte\\nlogik\\nboeser\\nkobold\n"*2)
>>> for line in file("tmp.txt"):
...     print line
...
\ntoerichte\nlogik\nboeser\nkobold

\ntoerichte\nlogik\nboeser\nkobold

>>> for line in codecs.open("tmp.txt", "r", "string_escape"):
...     print line
...

toerichte
logik
boeser
kobold


toerichte
logik
boeser
kobold

>>>

Peter



More information about the Python-list mailing list