python import module from different directory
ASHISH GUPTA
2 min read
- python
Introduction
Are you getting problem to import your python module from a different directory,To manage your folder structure of python project. don't worry in this blog we'll discuss about different ways to import a python module from a different directory to manage your folder structure.
How to Import a Python Module from a Different Directory
When you are working on a Python project, it's very common to organize code into multiple and different directories. Sometimes, you might need to import a module which located in a different directory. here are some method to import module from different directory.
Method 1
working on project with same directory but have different trees of folder in a root directory or main project folder.
*Above image is test3.py in sub folder have some basic module like multiplication of two number.
*Above image shows in main.py importing module of sub folder using folderName.fileName and calling the module t3.moduleName.
Method 2
Using "sys.path"
One of the easiest ways to import a module from a different directory is to update or modify the sys.path
list, which contains the directories Python searches for modules.
Steps
Locate the directory of the module which you want to import.
Add this directory to
sys.path
.Import the module.
code example:-
import sys
import os
# Add the directory to sys.path
module_dir = os.path.abspath('/path/to/your/module_directory')
if module_dir not in sys.path:
sys.path.append(module_dir)
# Now you can import your module
import your_module
Method 3
Using the "PYTHONPATH" in environment Variable
Another way to import module from different directories is by setting the PYTHONPATH
environment variable. This can be done in the terminal or within your code.
Setting PYTHONPATH
in the Terminal
Before running your Python script, set the PYTHONPATH
:
Terminal code:
export PYTHONPATH=$PYTHONPATH:/path/to/your/module_directory
python your_script.py
Setting PYTHONPATH
in Code
You can also set PYTHONPATH
in vsCode or other editor:
import os
import sys
# Add the directory to the PYTHONPATH
os.environ['PYTHONPATH'] = os.pathsep.join(['/path/to/your/module_directory', os.environ.get('PYTHONPATH', '')])
sys.path.append('/path/to/your/module_directory')
# Now you can import your module
import your_module
Conclusion
These all the several methods to import Modules from different directory in Python. like updating the "sys.path" , set environment variables in PYTHONPATH . each method have different use case , you can choose your own use cases that fits your code structure.
let's organize your project code properly and using these techniques, you can keep your projects clean and modular.
Thanks for reading this blog if you find any useful hit like button and follow for more solution of python problems.