How to open a txt file from the same folder as my module (w/outchanging the working dir)

S

Sergio Correia

I have a program in 'C:\Python25\Lib\site-packages\spam\spam.py'

Importing and everything works fine:
But the program calls a file located on the same folder (that is:
C:\Python25\Lib\site-packages\spam\).

How do i do that?

Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
datita = spam.eggs()
File "C:\Python25\lib\site-packages\spam\spam.py", line 149, in JustDoIt
config = open("configuration.txt", "rb").read().split('\r\n')
IOError: [Errno 2] No such file or directory: 'configuration.txt'

My last resort is to hard code the path for that file, but it's ugly,
and I want to know if I'm missing something. Am I?

Thanks a lot,
Sergio
 
L

Larry Bates

Sergio said:
I have a program in 'C:\Python25\Lib\site-packages\spam\spam.py'

Importing and everything works fine:
But the program calls a file located on the same folder (that is:
C:\Python25\Lib\site-packages\spam\).

How do i do that?

Traceback (most recent call last):
File "<pyshell#21>", line 1, in <module>
datita = spam.eggs()
File "C:\Python25\lib\site-packages\spam\spam.py", line 149, in JustDoIt
config = open("configuration.txt", "rb").read().split('\r\n')
IOError: [Errno 2] No such file or directory: 'configuration.txt'

My last resort is to hard code the path for that file, but it's ugly,
and I want to know if I'm missing something. Am I?

Thanks a lot,
Sergio

The problem is that C:\Python25\Lib\site-packages\spam is not
the current working directory when you run the program. If it were,
and if configuration.txt is in that directory it WILL find it. If
you are running this from a shortcut make the working directory
C:\Python25\Lib\site-packages\spam

-Larry
 
G

Gabriel Genellina

The problem is that C:\Python25\Lib\site-packages\spam is not
the current working directory when you run the program. If it were,
and if configuration.txt is in that directory it WILL find it. If
you are running this from a shortcut make the working directory
C:\Python25\Lib\site-packages\spam

If changing the working directory is not possible/convenient, use the
module __file__ attribute (spam.__file__) to obtain the directory where
spam.py resides.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,048
Latest member
verona

Latest Threads

Top