Skip to content

Python import file from parent directory

  • by

Python import file from the parent directory is not possible. If you try this leads to an error something like this.

ModuleNotFoundError: No module named ‘parentdirectory’

But you can add the parent directory to the sys.path using the append() method.

Python import file from the parent directory

Simple example code Importing modules from the parent folder. In order to import a module, the directory having that module must be present on PYTHONPATH.

import sys

# setting path

# importing
from modules.test import my_math

my_math.add(1000, 2000)

def add(a, b):
sum1 = a + b
return sum1

Output and complete code:

Python import file from the parent directory

Import from the parent directory using os.path.dirname method

import sys
import os

current = os.path.dirname(os.path.realpath(__file__))
parent = os.path.dirname(current)
import my_math

Do comment if you have any doubts or suggestions on this Python file topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *