[Tutor] Python file escaping issue?

spir denis.spir at free.fr
Mon Feb 22 08:37:21 CET 2010


Just a little complement to Steven's excellent explanation:

On Mon, 22 Feb 2010 10:01:06 +1100
Steven D'Aprano <steve at pearwood.info> wrote:

[...]

> So if you write a pathname like this:
> 
> >>> path = 'C:\datafile.txt'
> >>> print path  
> C:\datafile.txt
> >>> len(path)  
> 15
> 
> It *seems* to work, because \d is left as backlash-d. But then you do 
> this, and wonder why you can't open the file:

I consider this misleading, since it can only confuse newcomers. Maybe "lonely" single backslashes (not forming a "code" with following character(s)) should be invalid. Meaning literal backslashes would always be doubled (in plain, non-raw, strings). What do you think?

> But if the escape is not a special character:
> 
> >>> s = 'abc\dz'  # nothing special
> >>> print s
> abc\dz
> >>> print repr(s)
> 'abc\\dz'
> >>> len(s)
> 6
> 
> The double backslash is part of the *display* of the string, like the 
> quotation marks, and not part of the string itself. The string itself 
> only has a single backslash and no quote marks.

This "display" is commonly called "representation", thus the name of the function repr(). It is a string representation *for the programmer* only, both on input and output:
* to allow one writing, in code itself, string literal constants containing special characters, in a practical manner (eg file pathes/names)
* to allow one checking the actual content of string values, at testing time

The so-called interactive interpreter outputs representations by default. An extreme case:
>>> s = "\\"
>>> s
'\\'
>>> print s, len(s)
\ 1
>>> print repr(s), len(repr(s))
'\\' 4
>>> 
The string holds 1 char; its representation (also a string, indeed) holds 4.

> The best advice is to remember that Windows allows both forward and 
> backwards slashes as the path separator, and just write all your paths 
> using the forward slash:
> 
> 'C:/directory/'
> 'C:textfile.txt'

Another solution is to take the habit to always escape '\' by doubling it.


Denis
________________________________

la vita e estrany

http://spir.wikidot.com/


More information about the Tutor mailing list