How to import a Python module given the full path? - GeeksforGeeks (2024)

Improve

The Python module is a file consisting of Python code with a set of functions, classes, and variable definitions. The module makes the code reusable and easy to understand. The program that needs to use the module should import that particular module. In this article, we will discuss how to import a Python module given its full path.

Different Ways to Import Python Files

Various methods can be used to import the module by using its full path. here we are using some generally used methods for importing python files in Python those are following.

  • Using sys.path.append() Function
  • Using importlib Package
  • Using SourceFileLoader Class
  • Using exec() Function
  • Using imp Module
  • Using importlib.util.spec_from_file_location()

Consider the following file arrangement and let’s see how the above-listed methods can be used to import gfg.py module in main.py:

python
|--main.py
|articles
|--gfg.py

Below is the code for gfg.py

Python3

# class

class GFG:

# method

def method_in():

print("Inside Class method")

# explicit function

def method_out():

print("Inside explicit method")

Import Python File Using sys.path.append() Function

This is the easiest way to import a Python module by adding the module path to the path variable. The path variable contains the directories Python interpreter looks in for finding modules that were imported in the source files.

Syntax :

sys.path.append(“module_path”)

In this example Python code adds the ‘articles’ directory to the system path, allowing the import of the ‘gfg’ module. It then calls the ‘method_in’ from the ‘GFG’ class and ‘method_out’ from the ‘gfg’ module.

Python3

# importing module

import sys

# appending a path

sys.path.append('articles')

# importing required module

import gfg

from gfg import GFG

# accessing its content

GFG.method_in()

gfg.method_out()

Output:

Inside Class method
Inside explicit method

Import Python File Using importlib Package

The importlib package provides the implementation of the import statement in Python source code portable to any Python interpreter. This enables users to create their custom objects which helps them to use the import process according to their needs. The importlib.util is one of the modules included in this package that can be used to import the module from the given path.

Syntax:

module = importlib.util.spec_from_file_location(“module_name”, “module_path”)

In this example This code dynamically imports a module named “gfg.py” located in the “articles” directory, creates a new module object, and then executes methods “method_in” and “method_out” from the imported module “foo.GFG” and “foo,” respectively.

Python3

import importlib.util

# specify the module that needs to be

# imported relative to the path of the

# module

spec=importlib.util.spec_from_file_location("gfg","articles/gfg.py")

# creates a new module based on spec

foo = importlib.util.module_from_spec(spec)

# executes the module in its own namespace

# when a module is imported or reloaded.

spec.loader.exec_module(foo)

foo.GFG.method_in()

foo.method_out()

Output:

Inside Class method
Inside explicit method

Import Python File Using SourceFileLoader Class

SourceFileLoader class is an abstract base class that is used to implement source file loading with help of load_module() function which actually imports the module.

Syntax :

module = SourceFileLoader(“module_name”,”module_path”).load_module()

In this example code uses the `SourceFileLoader` from `importlib.machinery` to dynamically import a module named “gfg” from the file “articles/gfg.py”. It then calls the method `method_in()` from the class `GFG` within the imported module and the function `method_out()` from the imported module.

Python3

from importlib.machinery import SourceFileLoader

# imports the module from the given path

foo = SourceFileLoader("gfg","articles/gfg.py").load_module()

foo.GFG.method_in()

foo.method_out()

Output:

Inside Class method
Inside explicit method

Import Python File Using exec() Function

The `exec()` function in Python is a built-in function used for dynamic execution of Python code. It takes a string as input, interprets it as a sequence of Python statements, and executes them. This allows for runtime code generation and flexibility .

Syntax :

exec(code, globals=None, locals=None)

In this example code in `main.py` dynamically loads the “gfg.py” module using the `exec()` function. It reads the content of the file, compiles it, and executes it, allowing access to the module’s functions. Finally, it demonstrates usage by calling the “some_function()” from the dynamically imported “gfg.py” module.

Python3

# main.py

module_name = "gfg"

module_path = "./articles/gfg.py"

# Using exec() to dynamically load the module

with open(module_path, "r") as file:

code = compile(file.read(), module_path, 'exec')

exec(code)

# Now you can use the imported module

gfg_module = globals()[module_name]

# Example usage

gfg_module.some_function()

Output :

Inside Class method
Inside explicit method

Import Python File Using imp Module

The imp module in Python provides tools for working with modules, such as dynamically loading them. One common use is for importing modules based on a string name. The imp module has been replaced by the importlib module in newer Python versions.

In this example the below code uses the deprecated `imp` module to dynamically load the `gfg.py` module from the specified path and then invokes the function `some_function()` from that module.

Python3

import imp

# Specify the path to the gfg.py module

module_path = './articles/gfg.py'

# Load the module using imp.load_source

gfg_module = imp.load_source('gfg', module_path)

# Now you can use the functions or variables defined in gfg.py

gfg_module.some_function()

Output :

Inside Class method
Inside explicit method

Using importlib.util.spec_from_file_location()

The importlib.util module provides functions for working with the import system. The spec_from_file_location() function can be used to create a module specification from a file location, and module_from_spec() can be used to create a module from the specification.

Syntax :

spec = importlib.util.spec_from_file_location(module_name, file_path)

In this example code dynamically imports a module (`gfg.py`) using `importlib.util`, specifying the file path and a chosen module name. It creates a module specification, loads the module from the specification, and then allows the use of functions from the dynamically imported module (`gfg_module.some_function_in_gfg()`).

Python3

import importlib.util

# Specify the path to gfg.py

module_path = './articles/gfg.py'

module_name = 'gfg_module' # You can choose any name for the module

# Create a spec for the module

module_spec = importlib.util.spec_from_file_location(module_name, module_path)

# Load the module from the spec

gfg_module = importlib.util.module_from_spec(module_spec)

module_spec.loader.exec_module(gfg_module)

# Now you can use the gfg_module as if it were imported normally

gfg_module.some_function_in_gfg()

Output

Inside Class method
Inside explicit method


Last Updated : 29 Dec, 2023

Like Article

Save Article

Previous

Import Modules From Another Folder in Python

Next

Python - Remove numbers with repeating digits

Share your thoughts in the comments

Please Login to comment...

How to import a Python module given the full path? - GeeksforGeeks (2024)

FAQs

How to import a Python module given the full path? - GeeksforGeeks? ›

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

How do I import an entire Python module? ›

You need to use the import keyword along with the desired module name. When interpreter comes across an import statement, it imports the module to your current program. You can use the functions inside a module by using a dot(.) operator along with the module name.

How do I import a module from a specific folder in Python? ›

Python's sys. path. append() function is the most basic and commonly used method to import modules from different directories. When you're importing a module in Python, it searches for it in the directories listed in sys.

How to import own module in Python? ›

Example code
  1. #import the whole custom module.
  2. import validate.
  3. print("Let's check for validity :\n")
  4. number = '03001234567'
  5. #access the function insdie the imported module.
  6. if validate. validate_num(number):
  7. print('num is valid')

How do I import a Python module from the parent directory? ›

To import modules from the parent directory using os.path.dirname, follow these steps:
  1. Import the os and sys modules: ...
  2. Get the current directory and its parent directory using os.path.dirname: ...
  3. Add the parent directory to sys.path using the append() method: ...
  4. Import the desired module from the parent directory:
Nov 17, 2023

Top Articles
Latest Posts
Article information

Author: Laurine Ryan

Last Updated:

Views: 6116

Rating: 4.7 / 5 (77 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Laurine Ryan

Birthday: 1994-12-23

Address: Suite 751 871 Lissette Throughway, West Kittie, NH 41603

Phone: +2366831109631

Job: Sales Producer

Hobby: Creative writing, Motor sports, Do it yourself, Skateboarding, Coffee roasting, Calligraphy, Stand-up comedy

Introduction: My name is Laurine Ryan, I am a adorable, fair, graceful, spotless, gorgeous, homely, cooperative person who loves writing and wants to share my knowledge and understanding with you.