Python Forum

Full Version: Defining path
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have problem with defining paths to different folders to call different modules. To give an example,

folder1 > module1.py
folder2 > module2.py
folder3 > folder4 > module3.py, module4.py

I am also confused with the information on the net. What is the best way to define paths to different folders? How can I call a module in that defined folder?
The simplest way is to put the directories that contain the modules on the python path. In order to do this first run this in the python console to find your user site-packages directory
>>> import site
>>> site.getusersitepackages()
'/home/eric/.local/lib/python3.8/site-packages'
Now in this directory, create or update a file named usercustomize.py with the following lines (replace the names of the folders by the path to the actual folders in your file system)
# usercustomize.py
import sys
sys.path.extend(['folder1', 'folder2', 'folder3/folder4'])
That's it. Now you can import module1 ... module4 in your programs.
The next level is to be able to create a "package" instead of a module. Create the following files and directories structure
Output:
folder1 └── xdbv ├── bar.py ├── baz.py ├── foo.py └── __init__.py
Add folder1 to the python module path as shown in the previous post. You can now use imports such as
import xdbv.bar
from xdbv.foo import spam
from xdbv import baz
The presence of the __init__.py file makes "xdbv" a python package, i.e. a module containing submodules. These submodules could themselves be subpackages. The __init__.py file can be empty or it can contain code that will be executed the first time package xdbv is imported.