Alex Alex - 2 months ago 6
Python Question

Relative file paths in Python packages

How do I reference a file relatively to a package's directory?

My directory structure is:


/foo
package1/
resources/
__init__.py
package2/
resources/
__init__.py
script.py


script.py
imports packages
package1
and
package2
. Although the packages can be imported by any other script on the system. How should I reference resources inside, say,
package1
to ensure it would work in case
os.path.curdir
is arbitrary?

Answer

If you want to reference files from the foo/package1/resources folder you would want to use the __file__ variable of the module. Inside foo/package1/__init__.py:

from os import path
resources_dir = path.join(path.dirname(__file__), 'resources')