W3docs

Import a module from a relative path

To import a module from a relative path in Python, you can use the importlib.import_module() function from the importlib module.

To import a module from a relative path in Python, you need to understand that Python's import system relies on directories listed in sys.path rather than direct filesystem paths. You can either temporarily add the relative directory to sys.path or use importlib.util to load the module directly from a file.

Import a module from a relative path in Python using sys.path

import sys
import os

# Calculate the absolute path relative to the current script
relative_dir = os.path.join(os.path.dirname(__file__), 'subdir')
sys.path.append(relative_dir)

# Import the module
import mymodule

# Use the module
result = mymodule.some_function()

This adds the subdir directory to the Python search path and allows you to import mymodule using a standard import statement.

Import a module from a relative path in Python using importlib.util

For a cleaner approach that avoids modifying sys.path, you can use importlib.util.spec_from_file_location:

import importlib.util
import os

# Define the relative path to the module file
module_path = os.path.join(os.path.dirname(__file__), 'subdir', 'mymodule.py')

# Load the module from the path
spec = importlib.util.spec_from_file_location("mymodule", module_path)
mymodule = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mymodule)

# Use the module
result = mymodule.some_function()

This loads mymodule directly from the specified relative file path without altering the global search path.

Note that modifying sys.path can cause naming conflicts if multiple directories contain modules with the same name. Using importlib.util.spec_from_file_location is generally safer for temporary or one-off imports. For production code, it is usually better to structure your project as a proper Python package and use standard relative imports (from . import mymodule).