Menu Close

How to import a module from a relative path with Python?

Sometimes, we want to import a module from a relative path with Python.

In this article, we’ll look at how to import a module from a relative path with Python.

How to import a module from a relative path with Python?

To import a module from a relative path with Python, we can use the sys.path.insert method to register the path of the module.

For instance, we write

import sys
sys.path.insert(0, module_path)
import Bar

to call sys.path.insert to register module_path as a module directory.

Then we import Bar from module_path with

import Bar

Conclusion

To import a module from a relative path with Python, we can use the sys.path.insert method to register the path of the module.

Posted in Python, Python Answers