How to get the parent of the current directory in Python

In this tutorial, we are going to learn to get the parent of the current directory in Python. Python provides os module. This module helps to interact with the operating system. We will be working with functions like os.path.join, os.path.dirname, os.path.abspath and os.pardir.

Parent of the current directory in Python

I will describe the functions too.

Let’s begin…

In our first code snippet we will use os.getcwd(), os.path.join(), os.path.abspath() and os.pardir

  • os.getcwd() – This function is used for getting the current directory in Python
  • os.path.join() – This function is useful in joining string to the path intelligently using a directory separator ‘/’.
  • os.pardir() – This function gets the parent directory as string.
  • os.path.abspath() – This function normalizes the absolute version of the path. To get the parent directory this function requires os.path.join and os.pardir

Let’s implement these functions.

import os 
  
# current directory 
current_dir = os.getcwd() 
print("Present Directory", current_dir) 
  
# parent directory 
print(os.path.abspath(os.path.join(current_dir, os.pardir)))

Next trick to get the same result by simply using os.path.dirname() function.

par_dir = os.path.dirname(current_dir) 
print("Parent directory", par_dir)

The above methods only return one level parent directory. The earlier methods fail in getting the parent of the parent directory. However, we will not only get the parent of the parent directory but create a function called get_parent and get the parent directory mentioned by the user.

For such problems Python provides os.path.relpath() function. This function returns the relative file path. The trick is to simply apply os.path.dirname() inside the for loop and iterate it over level+1 times. This will return the starting point and as a result os.path.relpath() will give the relative path.

# function to get parent directory
def getParentDir(CurrentPath, levels = 1): 
    current_new = CurrentPath
    for i in range(levels + 1): 
   
        current_new = os.path.dirname(current_new) 
  
   
    return os.path.relpath(CurrentPath, current_new)
path = os.getcwd()
print(getParentDir(path, 2))

Also read: Simplify the directory path in Python

Leave a Reply

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