How to Import from Parent Directory in Python

To import from a parent directory in Python, set the path to the system absolute path. We can import modules from the current working directory. But, we cannot import the modules from the parent directory. We can import the child directory by specifying the current module followed by the dot and the child module name.

To import a file in Python, use the import statement.

Let’s now consider the hierarchy in which the file is stored in the directory.

  •   root
    •  Parent_directory
      • child1.py
      • __init__.py
      •  Current_directory
        • current.py
        • sample.py
        •  __init__.py

In this case, the sample.py is the file we are working with. If we want to import the file child1.py in this sample.py file, an error is raised called the ModuleNotFoundError. Hence, we must use the proper import statement to overcome this error.

Let us consider the code in the child1.py file.

def sum(a, b):
  return a + b

Now, let us see the code in the sample.py file.

from parent_directory import child1

a = 10
b = 20
print(child1.sum(a, b))

In this program, we created a child1.py file in the parent directory, which has a function called sum(). The sum() function returns the sum of two numbers.

Then, inside the current directory, we created a sample.py file. We have imported the child1 module from the parent directory in this file. Then, we called the sum() function present in the module from the sample.py file.

If we execute this program, an error is raised. This error is called the ModuleNotFoundError. The module parent_directory is not found because the child directory cannot access the parent directory. 

To solve this problem, we can use a “.” before the parent directory.

Now, we are in the current directory. To access the parent directory, we must move to the root directory. Hence, it takes two steps to reach the root directory. First, we have to add two dots before the parent directory from the statement.

We can do this only if we have used the __init__ file in the directory. This __init__ file makes the directory a package. Hence, when we run this, we will get the result.

We can import files from the parent directory by adding this path to the absolute path. 

import os
import sys
from parent_directory import child1

p = os.getcwd()
sys.path.insert(0, p)
a = 10
b = 20
print(child1.sum(a, b))

If we execute this program, then the child module will be imported. So now we can see that we have accessed the file in the parent class from the child directory. We can do this by adding the path to the system environment path.

That’s it for this tutorial.

Related posts

How to Implement Interface in Python

How to Copy Files in Python

How to Convert File to tar.gz in Python

Leave a Comment