Import Modules From Another Folder in Python
Last Updated :
17 Jun, 2021
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
Python3
def run():
print ( "Module 0 imported successfully" )
|
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.
Python3
import sys
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.
Python3
import sys
sys.path.insert( 0 , "C:\\Users\\anila\\Desktop\\Task\\modules" )
import module0
module0.run()
|
Output:
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:
Python3
import module0
module0.run()
|
Output:
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...