How do I import a Python module given its relative path?
For example, if dirFoo
contains Foo.py
and dirBar
, and dirBar
contains Bar.py
, how do I import Bar.py
into Foo.py
?
Here's a visual representation:
dirFoo\
Foo.py
dirBar\
Bar.py
Foo
wishes to include Bar
, but restructuring the folder hierarchy is not an option.
Best Answer
Assuming that both your directories are real Python packages (do have the
__init__.py
file inside them), here is a safe solution for inclusion of modules relatively to the location of the script.I assume that you want to do this, because you need to include a set of modules with your script. I use this in production in several products and works in many special scenarios like: scripts called from another directory or executed with python execute instead of opening a new interpreter.
As a bonus, this approach does let you force Python to use your module instead of the ones installed on the system.
Warning! I don't really know what is happening when current module is inside an
egg
file. It probably fails too.