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. This function allows you to import a module by specifying its name and the relative path to the module.

Here's an example of how you can use importlib.import_module() to import a module called mymodule.py that is located in a subdirectory called subdir:

import importlib

# Import the module
module = importlib.import_module('subdir.mymodule')

# Use the module
result = module.some_function()

This will import the mymodule module from the subdir subdirectory and make it available for use in your code.

Watch a course Python - The Practical Guide

You can also use the sys.path list to add the directory containing the module to the Python search path, and then use the import statement to import the module. However, you should provide the absolute path to the sys.path.append method.

For example:

import sys

# Add the directory to the search path
sys.path.append('/path/to/subdir')

# Import the module
import mymodule

# Use the module
result = mymodule.some_function()

This will add the subdir directory to the Python search path and then import the mymodule module from that directory.

Note that using importlib.import_module() or modifying the sys.path list is generally not recommended, as it can make your code more difficult to understand and maintain. It is usually better to use the standard Python import mechanism or to use the PYTHONPATH environment variable to specify the search path.