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

Larry Bates larry.bates at websafe.com
Thu Apr 5 01:14:37 CEST 2007


Sergio Correia wrote:
> I have  a program in 'C:\Python25\Lib\site-packages\spam\spam.py'
> 
> Importing and everything works fine:
>>>> from spam import spam
> 
> But the program calls a file located on the same folder (that is:
> C:\Python25\Lib\site-packages\spam\).
> 
> How do i do that?
> 
>>>> spam.eggs()
> 
> 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



More information about the Python-list mailing list