Search code examples
pythonpackagedirectory-structure

File path relative to where it was imported


I have:

project
|--__init__.py
|--...
+--package1
|  |--__init__.py
|  |--...
+--dbs
   |--...

Where project is a collection of packages to be imported and used by the user. The names are just an example.

Now, some files under project/package1/ need to access some files in project/dbs/, but depending on where the user placed the project folder and from where he or she imported it, path/to/project/dbs/file is not the same. Because of this issue and for other purposes I thought I should have a variable projectroot defined as the root of the project, relative to where it was imported from. For instance:

If the user has ~/Desktop/project and imported it from ~/ then projectroot would be Desktop/project, and path/to/project/dbs/file would be "%s/dbs/file" % (projectroot). Is this really needed? If so, what is the best way of doing it?


I tried using this in project/pathtfinder.py and used project/__init__.py as

import pathfinder
projectroot=pathfinder.module_path()
import package1

But when I run import project I get

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "project/__init__.py", line 3, in <module>
    import package1
  File "project/package1/__init__.py", line 5, in <module>
    db = sqlite3.connect("%s/dbs/main.db" % projectroot)
  NameError: name 'projectroot' is not defined

And if use print projectroot just after defining it I get Desktop/project, as expected.


Solution

  • You need to add the path of project to the PYTHONPATH