Menu Close

How to import modules from parent folder with Python?

Sometimes, we want to import modules from parent folder with Python.

In this article, we’ll look at how to import modules from parent folder with Python.

How to import modules from parent folder with Python?

To import modules from parent folder with Python, we register the module’s folder with sys.path.insrt.

Then we can import the module.

For instance, we write

import os
import sys
import inspect

currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
parentdir = os.path.dirname(currentdir)
sys.path.insert(0, parentdir) 

import mymodule

to call os.path.dirname with os.path.abspath(inspect.getfile(inspect.currentframe())) to get the path of the current file’s directory.

And then we get the parent’s path with os.path.dirname(currentdir).

Then we register the parent’s path with sys.path.insert(0, parentdir) .

Finally we import the module in parentdir with

import mymodule

Conclusion

To import modules from parent folder with Python, we register the module’s folder with sys.path.insrt.

Then we can import the module.

Posted in Python, Python Answers