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.
instead of:
just in case there could be another dirBar installed and confuse a foo.py reader.
Look at the pkgutil module from the standard library. It may help you do what you want.
Well, as you mention, usually you want to have access to a folder with your modules relative to where your main script is run, so you just import them.
Solution:
I have the script in
D:/Books/MyBooks.py
and some modules (like oldies.py). I need to import from subdirectoryD:/Books/includes
:Place a
print('done')
inoldies.py
, so you verify everything is going OK. This way always works because by the Python definitionsys.path
as initialized upon program startup, the first item of this list,path[0]
, is the directory containing the script that was used to invoke the Python interpreter.If the script directory is not available (e.g. if the interpreter is invoked interactively or if the script is read from standard input),
path[0]
is the empty string, which directs Python to search modules in the current directory first. Notice that the script directory is inserted before the entries inserted as a result ofPYTHONPATH
.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.The easiest method is to use sys.path.append().
However, you may be also interested in the imp module. It provides access to internal import functions.
This can be used to load modules dynamically when you don't know a module's name.
I've used this in the past to create a plugin type interface to an application, where the user would write a script with application specific functions, and just drop thier script in a specific directory.
Also, these functions may be useful:
Here's a way to import a file from one level above, using the relative path.
Basically, just move the working directory up a level (or any relative location), add that to your path, then move the working directory back where it started.