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. To import a module, the directory having that module must be present on PYTHONPATH.
main.py
import sys
# setting path
sys.path.append('../modules')
# importing
from modules.test import my_math
my_math.add(1000, 2000)
my_math.py
def add(a, b):
sum1 = a + b
print(sum1)
return sum1
Output and complete code:
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)
sys.path.append(parent)
import my_math
my_math.add()
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.