[Tutor] Window pathnames
Jeff Shannon
jeff at ccvcorp.com
Fri Oct 3 17:24:46 EDT 2003
Zandbergen Christian wrote:
> >>> open("C:\\dslfjsl\jlsfjslfsj")
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> IOError: [Errno 2] No such file or directory:
> 'C:\\dslfjsl\\jlsfjslfsj'
>
>
> It seems that one backslash always returns a double backslash.
That's not quite true. Try typing in a directory name that starts
with a 't', for example (like "c:\\stuff\temp"), and you won't get a
double backslash in the error message -- but you might see an
indication of why all this happens.
'\t' isn't really a backslash and a 't', as Python sees it -- instead,
it's a single TAB character (ascii code 0x09). So the string I showed
above is interpreted by Python as meaning "c:\stuff[TAB]emp". There's
a variety of these nonprintable characters, and they're accessed by
using a backslash to "escape" the following character -- a backslash
in a string says "Treat the next character special", and then the next
character indicates *what* to do.
So how do you get a backslash, then, if it means to treat the next
character as something special? Well, you make the next character
another backslash, and the "special" handling in this case is to just
print it as it is. When Python is displaying a string using repr()
(as error tracebacks do), it shows escape sequences as they would be
typed; thus, a string containing a (single) backslash will be
displayed by repr() by using two backslashes.
Now, not all characters indicate something special when escaped. For
instance, '\j' has no special meaning. So Python reads that as two
separate characters, a backslash and a 'j', when you type it in.
However, when it displays backslashes, it doubles them (so that you
don't mistake them for part of an escape code). That's what's
happening in your error message.
Jeff Shannon
Technician/Programmer
Credit International
More information about the Tutor
mailing list