How to use os.path.relpath() and os.path.dirname() In Python
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.Return Type: This method returns a string value which represents the relative file path to given path from the start directory.0222
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.
Example:
Python3
# 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 / w3wiki / Nikhil / gfg.txt' print (getParent(path, 2 )) |
Output:
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()
- Using os.path.dirname()
- Using os.path.relpath() and os.path.dirname()
- Using Path().resolve().parent