Import Modules From Another Folder in Python
In this article, we are going to see how to import a module from another folder, While working on big projects we may confront a situation where we want to import a module from a different directory, here we will see the different ways to import a module form different folder.
It can be done in two ways:
- Using sys.path
- Using PythonPath.
Create a module for demonstration:
File name: module0.py
Method 1: Using sys.path
sys.path: It is a built-in variable within the python sys module. It contains a list of directories that the interpreter will search in for the required modules.
In this approach, Insert or Append the path of the directory containing the modules in sys.path.
Example: Suppose we need to import the following modules from “Desktop\\Task\\modules” in “Desktop\\VScode\\Projects\\ImportModule\\main.py”.
Insert/Append the path to sys.path and import module0 present in the directory and call its run function.
Method 2: Using PYTHONPATH
PYTHONPATH : It is an environment variable which you can set to add additional directories where python will look for modules and packages.
Open a terminal or command prompt and enter the following command:
Syntax: set PYTHONPATH=path_to_module_folder
Add the path to PYTHONPATH and import module0 present in the directory and call its run function.
Below is the implementation:
Please Login to comment...