Python - Import from parent directory - GeeksforGeeks

30 May, 2021
In this article, we will learn how to Import a module from the parent directory. From Python 3.3, referencing or importing a module in the parent directory is not allowed, From the below example you can clearly understand this.
structure of directory 
In the parent directory, we have a subdirectory, geeks.py file and in the subdirectory, we have a python file named temp.py, Now let’s try if we can import the geeks module in the parent directory from the temp.py file in the subdirectory.
geeks.py (module in the parent directory)
Python3
def geek_method():    print("This method in geeks module.......bye")
temp.py (python file in sub directory)
Python3
# importing the module in# parent directoryfrom parentdirectory import geeks  # calling the func1() method # from geeks modulegeeks.geek_method()
As we have discussed earlier it is not possible to import a module from the parent directory, so this leads to an error something like this.
Traceback (most recent call last):
 File “C:/Users/sai mohan pulamolu/Desktop/parentdirectory/subdirectory/temp.py”, line 2, in <module>
   from parentdirectory import geeks
ModuleNotFoundError: No module named ‘parentdirectory’
Now let’s learn how to import a module from the parent directory:
In order to import a module, the directory having that module must be present on PYTHONPATH. It is an environment variable that contains the list of packages that will be loaded by Python. The list of packages presents in PYTHONPATH is also present in sys.path, so will add the parent directory path to the sys.path.
For our work, we use three different approaches that are explained below with the help of examples.
Method1: Here we will use sys module and set the path directly to the required module.
Add the parent directory to the sys.path using the append() method. It is a built-in function of sys module that can be used with a path variable to add a specific path for interpreters to search. The following example shows how this can be done.
Code:
Python3
import sys  # setting pathsys.path.append('../parentdirectory')  # importingfrom parentdirectory.geeks import geek_method  # usinggeek_method()
Output:
This method in geeks module.......bye
Method 2: Here we will use sys module as well as the path module for getting the directory and set the path directly to the required module.
Syntax: os.path.abspath(path)
Parameter:Path: A path-like object representing a file system path.
Return Type: This method returns a normalized version of the pathname path.
Firstly we will get the name of the directory where the temp.py file is presently using the path.path(__file__).abspath(), secondly add the directory to the sys.path.append to check, we will use its method.
Code:
Python3
import pathimport sys  # directory reachdirectory = path.path(__file__).abspath()  # setting pathsys.path.append(directory.parent.parent)  # importingfrom parentdirectory.geeks import geek_method  # usinggeek_method()
Output:
 This method in geeks module.......bye
Method 3: Here we will use sys module as well as the os module for getting the directory (current as well as parent) and set the path directly to the required module.
Syntax: os.path.dirname(path)
Parameter:path: A path-like object representing a file system path.
Return Type: This method returns a string value which represents the directory name from the specified path.
Firstly we will get the current directory by using the os.path.dirname(os.path.realpath(__file__)), secondly, we will get the parent directory by using the os.path.dirname(), finally, add the parent directory to the sys.path to check, we will use its method.
Code:
Python3
import sysimport os  # getting the name of the directory# where the this file is present.current = os.path.dirname(os.path.realpath(__file__))  # Getting the parent directory name# where the current directory is present.parent = os.path.dirname(current)  # adding the parent directory to # the sys.path.sys.path.append(parent)  # now we can import the module in the parent# directory.import geeks    geeks.geek_method()
Output:
Picked
Python directory-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list