Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 362
Alex Avatar asked Jun 18 '09 07:06

Alex


1 Answers

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')
like image 57
Alex Morega Avatar answered Oct 28 '22 03:10

Alex Morega