[Tutor] absolute locations

Gonçalo Rodrigues op73418 at mail.telepac.pt
Thu Jan 8 16:45:40 EST 2004


Em Thu, 8 Jan 2004 12:22:52 -0800 (PST), Christopher Spears
<cspears2002 at yahoo.com> atirou este peixe aos pinguins:

>Grrr!
>
>I'm trying to open up a file with the following
>absloute path in Windows 2000:
>
>C:\Documents and Settings\Christstopher Spears\My
>Documents\python\unit4.txt
>
>So I enter the following in IDLE:
>
>>>> import os
>>>> fileName = os.path.join("c:", "Documents and
>Settings", "Christopher Spears", "My Documents",
>"python", "unit4.txt")
>>>> fileobject = open(fileName, 'r')
>
>Traceback (most recent call last):
>  File "<pyshell#2>", line 1, in -toplevel-
>    fileobject = open(fileName, 'r')
>IOError: [Errno 2] No such file or directory:
>'c:Documents and Settings\\Christopher Spears\\My
>Documents\\python\\unit4.txt'
>

The answer is right there in the traceback. 

Look at the *right* way to do it:

>>> fileName = os.path.join("c:\\Documents and Settings", "Christopher Spears", "My Documents", "python", "unit4.txt")
>>> fileName
'c:\\Documents and Settings\\Christopher Spears\\My
Documents\\python\\unit4.txt'
>>> 

Do you notice the difference?

>I know unit4.txt is there, but I can't seem to
>convince python of that!  What is up with \\ anyway?

The character \ is special, it's the escape character. For example

"\n"

means new line, e.g.

>>> print "A sentence and a newline\n"
A sentence and a newline

>>> 

This means that if you want Python to interpret \ literally you have
to use some scheme - hence the doubling \\.

Hope it helps,
G. Rodrigues



More information about the Tutor mailing list