raw strings and \

Duncan Booth duncan.booth at invalid.invalid
Sun Mar 5 04:37:03 EST 2006


 wrote:

> I thought I understood raw strings, then I got bitten by this:
> 
> x=r'c:\blah\'
> 
> which is illegal!  I thought that \ had no special meanning in a raw
> string so why can't it be the last character?

No, the backslash is still special in terms of parsing the string, it 
is simply that once the string has been parsed escape sequences are not 
interpreted.

> 
> making me do:
> 
> x=r'c:\blah' '\\'
> 
> is just silly...
> 
> 
Yes, that is silly. You could alternatively do:

x = 'c:/blah/'

or

x = 'c:\\blah\\'

But why would you want to end your path with a literal backslash anyway? 
Get into the habit of using the os.path module for all manipulations of 
file paths and you never need to worry about this sort of thing again.

This sort of thing should work well enough:

folder = 'c:/blah'

for line in open(os.path.join(folder, 'data.txt')):
   print line



More information about the Python-list mailing list