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
- path: It is a path-like object that represents the file system path.
- 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
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
Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.