The Wayback Machine - https://web.archive.org/web/20240213201303/https://www.geeksforgeeks.org/import-modules-from-another-folder-in-python/
Open In App
Related Articles

Import Modules From Another Folder in Python

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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")

                    

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.

Python3

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.

Python3

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:

Python3

# Import the module0 directly since 
# the current path is of modules.
import module0
  
# Prints "Module0 imported successfully"
module0.run()

                    

Output:


Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.


Last Updated : 17 Jun, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads
Complete Tutorials