Get parent of current directory using Python

In Python, OS module is used to interact with the operating system. It comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. The *os* and *os.path* modules include many functions to interact with the file system.

OS module provides various ways for getting the parent directory. Some of the ways are:

Using os.path.abspath()

os.path.abspath() can be used to get the parent directory. This method is used to get the normalized version of the path. This function also needs the help of os.path.join() and os.pardir().
os.path.join() method in Python join one or more path components intelligently. This method concatenates various path components with exactly one directory separator (‘/’) following each non-empty part except the last path component. If the last path component to be joined is empty then a directory seperator (‘/’) is put at the end.

Syntax: os.path.abspath(path)

Parameters:
path: A path-like object representing a file system path.



Return Type: Returns a string that is a normalized version of the path.

Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to get parent
# directory 
  
  
import os
  
# get current directory
path = os.getcwd()
print("Current Directory", path)
  
# prints parent directory
print(os.path.abspath(os.path.join(path, os.pardir)))

chevron_right


Output:
python-parent-directory

Using os.path.dirname()

os.path.dirname() method in Python is used to get the directory name from the specified path.

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.

Example:



filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to get parent
# directory
  
  
import os
  
# get current directory
path = os.getcwd()
print("Current Directory", path)
print()
  
# parent directory
parent = os.path.dirname(path)
print("Parent directory", parent)

chevron_right


Output:

python-parent-directory

Using os.path.relpath() and os.path.dirname()

In the above examples, getting the parent directory was limited to one level, i.e. we were only able to get the parent of current directory upto one level only. Suppose we want to find the parent to the parent directory, then the above code fails. This can be achieved by using os.path.relpath() and os.path.dirname() together.

os.path.relpath() method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory.

Syntax: os.path.relpath(path, start = os.curdir)

Parameter:
path: A path-like object representing the file system path.
start (optional): A path-like object representing the file system path.
The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory.

A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a string value which represents the relative file path to given path from the start directory.0222

Example:

To get the parent directory according to levels specified by the user, we will create a function getParent() which will take path and levels as arguments. Inside the function, a for loop will iterate level+1 numbers of time and os.path.dirname() will be called inside the for loop. Calling this function inside the for loop will give us the starting point from which os.path.relpath() will give the relative file path.

Below is the implementation.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python program to get the
# parent directory
  
  
import os.path
  
# function to get parent
def getParent(path, levels = 1):
    common = path
  
    # Using for loop for getting
    # starting point required for
    # os.path.relpath()
    for i in range(levels + 1):
  
        # Starting point
        common = os.path.dirname(common)
  
    # Parent directory upto specified
    # level
    return os.path.relpath(path, common)
  
path = 'D:/Pycharm projects / GeeksforGeeks / Nikhil / gfg.txt'
print(getParent(path, 2))

chevron_right


Output:

python-parent-directory




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



Improved By : kunalmalvi18