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

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Apr 4 21:04:15 EDT 2007


En Wed, 04 Apr 2007 20:14:37 -0300, Larry Bates <larry.bates at websafe.com>  
escribió:

> 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?
>
> 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.

-- 
Gabriel Genellina




More information about the Python-list mailing list