[Tutor] Reading escaped characters from a file

wesley chun wescpy at gmail.com
Sat Oct 14 18:07:43 CEST 2006

> I have code that uses variables to hold escaped characters like "\n" or
> "\03". As long as the assignment is done within the code, like self.crChar =
> "\n", there is no problem. But When I try to read the same character string
> from a text file and assign it, the string is seen as just a string of
> characters instead of an escape sequence, and the program fails.
>    :
> When I print "self.crChar", it displays "\\n" and
> it doesn't behave like a carriage return.


the problem is that when you're doing it "live", Python translates the
\n as a single character, NEWLINE.  when you are reading those same
characters from disk, what it reads is '\' followed by 'n' because
that's what stored in the file and the reason why you get '\\n', which
is the same as r'\n', a raw string.

in "\n" the backslash is used to "escape the n," meaning to realize
the special symbol \n.  in "\\n", the (frontmost) backslash is used to
escape the 2nd backslash, telling Python to take the backslash
verbatim and to take the following 'n' as-is.

in order to read in a NEWLINE, you have to just store a blank line to
the disk file. off the top of my head, i can't think of a way to
"eval" a '/' and 'n' to convert it into a \n... perhaps someone else
here can help with that.

-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca

More information about the Tutor mailing list