ERROR: how to use a text file in a module?

Rhodri James rhodri at wildebst.demon.co.uk
Thu Jun 18 18:42:55 EDT 2009


On Thu, 18 Jun 2009 19:57:46 +0100, Moni GV <tamuzija at yahoo.es> wrote:

> Help with a "No such file ..." error. I have the next folder structure:
> ---Network contains:
>     --packets.py
>     --Temp contains:
>        -test.py
>
> Well, within packets.py I do this:
> from Temp.test import *

Wildcarded imports like this aren't often a good idea.  It has
nothing to do with your problem, I just thought I'd mention it.

> Within test.py I do this:
> f = open ("topo.txt", "r")
>
> The error is:
> No such file "topo.txt"
>
> However, when I execute test.py, without using neither packets.py nor  
> the folder structure, there is no error, because topo.txt exists.

Where does topo.txt exist?  In the Temp directory?

I'll take a wild stab in the dark, and suggest that the way you ran
your program the first time (to get the error) was approximately
like this (depending on your operating system):

cd Network
python packets.py

Am I right?  And for the second time (when it worked) was:

cd Network/Temp
python test.py

roughly what you did?  Assuming that I'm right, notice that
you are in different directories each time.  Python will look
for a file called "topo.txt" in the *current* directory (i.e.
where you "cd"ed to) each time, *not* in the same directory
as test.py.

(If you double-clicked on the files, I think that's equivalent
to the situations I outlined above.  I certainly wouldn't want
to trust where the current directory was in that case!)

To fix this, you either need to be consistent about how you
run your program and change the filename appropriately (i.e.
writing 'open("Temp/topo.txt", "r")' instead), or you need to
fix where 'topo.txt' is supposed to be relative to your home
directory or the filesystem root and change the filename to
match it (as in 'open("/usr/local/lalala/topo.txt", "r")' or
'open("~/Network/Test/topo.txt", "r")', or the equivalent on
Windows).

-- 
Rhodri James *-* Wildebeest Herder to the Masses



More information about the Python-list mailing list