Skip to content

Python import module from path | Example code

How to import a Python module given the full path?

The python module is a kind of code file containing a set of functions, classes, and variables definitions. With the module, you can make code reusable and easy to understand. To use module code you have to import it.

Here are some methods to import the module by using its full path:

  • sys.path.append() Function
  • importlib Package
  • SourceFileLoader Class

Example import module from a path in Python

Simple examples code: consider this is project file and modules structure:-

Python import module from path

main.py code for all example

var = "Hello main file"
num = 9876543210


def greeting(name):
    print("Hello, " + name)

Using sys.path.append() Function

The path variable contains the directories the Python interpreter looks in for finding imported modules in the source files.

import sys

# appending a path
sys.path.append('modules')

from modules import main

print(main.num)

Output: 9876543210

Using importlib Package

The importlib.util is one of the modules included in this package that can be used to import the module from the given path.

import importlib.util

spec = importlib.util.spec_from_file_location("main", "modules/main.py")

foo = importlib.util.module_from_spec(spec)

spec.loader.exec_module(foo)

print(foo.var)

Output: Hello main file

Using SourceFileLoader Class

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

from importlib.machinery import SourceFileLoader

# imports the module from the given path
foo = SourceFileLoader("main", "modules/main.py").load_module()

foo.greeting("Kevin")

Output: Hello, Kevin

Do comment if you have any doubts or suggestions on this Python module topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

1 thought on “Python import module from path | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading