__file__ is sometimes absolute, sometimes relative

Christian Heimes lists at cheimes.de
Fri Oct 1 07:47:14 EDT 2010


Am 01.10.2010 13:00, schrieb Sébastien Barthélemy:
> Hello,
> 
> I use a data file that lies on disk in the same directory that the
> module which makes use of it.
> 
> The data file is checked in the repository and gets installed by
> the distutils ``package_data`` directive, so it is in place both
> during development and after and install.
> 
> In my program, I need to find the absolute path to this data file.
> 
> I could think of 3 ways to do this:
> 1. using the __path__ property in the module
> 2. using __file__ property in the module
> 3. using __file__ and os.getcwd() in the module

Use the abspath function of the os.path module:

HERE = os.path.dirname(os.path.abspath(__file__))

Christian




More information about the Python-list mailing list