Working of os.path.relpath() method in Python

We use the os module in Python for interacting with the operating system. The os module comes with various sub-modules that can be used depending upon the kind of task we need to perform.

One such sub-module in Python is the os.path sub-module, which is used for some common path manipulations. It provides functions to work with the absolute paths and the relative paths.  Here we will look into the os.path.relpath() method of os module and how this method works.

Syntax for os.path.relpath() in Python

The syntax to call this method would be os.path.relpath(path, start).
This method takes two parameters. The first parameter is a mandatory one and is a path whose relative path has to be given. The start parameter is an optional parameter.  The relative path of the path we are trying to get, is given with respect to the path passed as an argument while calling the relpath() function(which is the second parameter). If no starting path is mentioned, the relative path will be given to us with respect to the current working directory.
A point to note here is, that this method only computes the relative path, the existence of the given path or the given directory is not checked.

import os 
# with the start path 
path = "/home / User / Desktop / folder1 / file.ppt" 
init = "/home / User" 
rel_path = os.path.relpath(path, init) 

# without the starting path
path = "/home / User / Desktop / folder2 / subfolder / file.ppt"
rel_path = os.path.relpath(path) 



..\ User \ Desktop \ folder1 \ file.ppt
..\..\home \ User \ Desktop \ folder2 \ subfolder \ file.ppt
  • Here, the first relative path was computed with respect to the start path that was mentioned.
  • Whereas, in the second one, we did not mention any start path. Therefore, the current directory was taken by default and hence the relative path was calculated.

Also read: Get the position of max value in a list in Python

Leave a Reply

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