Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Defining path
#1
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?
Reply
#2
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.
erdemath likes this post
Reply
#3
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.
erdemath likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  WebDriverException: Message: 'PATH TO CHROME DRIVER' executable needs to be in PATH Led_Zeppelin 1 2,150 Sep-09-2021, 01:25 PM
Last Post: Yoriz
  .pth file does not show up in sys.path when configuring path. arjunsingh2908 2 5,672 Jul-03-2018, 11:16 AM
Last Post: arjunsingh2908

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020