python · March 26, 2023 0

How to import a Python module given the full path?

Table of Content

There are several ways to import a Python module given the full path to the module file. Here are some possible solutions:

  1. Using importlib.import_module() function:
    
    import importlib.util

module_path = '/path/to/module.py'
module_name = 'module_name'

spec = importlib.util.spec_from_file_location(module_name, module_path)
module = importlib.util.module_from_spec(spec)
spec.loader.exec_module(module)


2. Using importlib.machinery.SourceFileLoader() function:

from importlib.machinery import SourceFileLoader

module_path = '/path/to/module.py'
module_name = 'module_name'

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


3. Adding the directory containing the module file to sys.path and then importing the module using its name:

import sys
import os

module_path = '/path/to/module'
module_name = 'module_name'

sys.path.append(os.path.abspath(module_path))
module = import(module_name)



In all these examples, module_path refers to the full path of the module file, including the filename and extension, and module_name refers to the name that you want to give to the module when you import it.

Note that importing a module dynamically using its full path can be less efficient and less safe than importing it using its name. It also can be platform-dependent, as the required path separator may differ between operating systems.
%d bloggers like this: