[Tutor] Reading escaped characters from a file

Luke Paireepinart rabidpoobear at gmail.com
Sat Oct 14 18:04:22 CEST 2006


David Heiser wrote:
>  
> 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.
>  
> I read the "parameter = value" pairs, like "crChar = \n", from an 
> ASCII file and store them in a dictionary; "parameterDict[parameter] = 
> value". Then I assign the value to the variable using "self.crChar = 
> parameterDict["crChar"]. When I print "self.crChar", it displays "\\n 
> <file://%5C%5Cn>" and it doesn't behave like a carriage return.
Please include the code that is causing you trouble instead of trying to 
sum up what you think the problem is.
Quite often the problem is just a simple syntax or other error that the 
beginner may overlook that we can help by pointing out to you.

In this situation, I believe what's happening is that you expect this:

#ascii text file
hello, world!\n
#----- end

to be read into python as

 >>> f.readlines()[0] == 'hello, world!\n'
True

but no, that's not what the file says.
The file says 'hello, world \\n' because you can see an actual \ in the 
file text, right?
So in python it'll be represented by a double-backslash.

The actual \n is an escape code, you can't ever see it in files.
In the file

#start
a
b
c
d
e
#end

 >>> print f.readlines()
['a\n','b\n','c\n','d\n','e\n']

You don't explicitly put \n in a text file to have a string with \n at 
the end.
You hit enter at the end of the line.


>  
> Can anyone guide me toward a resolution?
>  
> ------------------------------------------------------------------------
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list