Python os.path.relpath() Method

Python os.path.relpath() method is used to calculate the relative file path to a given destination from a specified start directory.

It returns a relative file path from the ‘start’ path to the ‘path’. Both ‘path’ and ‘start’ have to be strings representing file paths. 

The os.path.relpath() automatically normalizes the resulting path, taking care of ‘..’ and ‘.’ parts.

Syntax

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

Parameters

  1. path: It is a path-like object that represents the file system path.
  2. start: It is an optional argument, a path-like object representing the file system path.

Return value

It returns a string value representing the relative file path to the given path from the start directory.

Visual Representation

Visual Representation of Python os.path.relpath() Method

Example

import os

path = "/Users/krunal/Desktop/code/pyt/database"
 
start = "/Users/krunal"

relative_path = os.path.relpath(path, start)

print(relative_path)

Output

Desktop/code/pyt/database

That’s it.

Related posts

Python os.path.exists()

Python os.path.split()

Python os.path.isfile()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.