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
def run():
print ( "Module 0 imported successfully" )
|
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.
import sys
# Prints the list of directories that the # interpreter will search for the required module. print (sys.path)
|
Output:
In this approach, Insert or Append the path of the directory containing the modules in sys.path.
Syntax:
sys.path.insert(0, path)
sys.path.append(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.
import sys
# Insert the path of modules folder sys.path.insert( 0 , "C:\\Users\\anila\\Desktop\\Task\\modules" )
# Import the module0 directly since # the current path is of modules. import module0
# Prints "Module0 imported successfully" module0.run() |
Output:
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:
# Import the module0 directly since # the current path is of modules. import module0
# Prints "Module0 imported successfully" module0.run() |
Output: