How to find the relative path of a file in python

How to find the relative path of a file in python:

To find the relative path to a file in python, we can use os module. os package is available in python and we don’t have to install anything to use it. This package provides a method called os.path.relpath that can be used to find the relative path either from the current directory or from a given directory.

In this post, we will learn how to use os.path.relpath to find the relative path.

Definition of os.path.relpath:

os.path.relpath is defined as below:

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

It returns the relative file path to path from the current directory or from the start directory. The start directory is optional. If we don’t provide it, it takes the current directory or os.curdir.

Let’s try it with different examples.

Python program:

Let’s take a look at the below example:

import os

path = '/Users/cvc/Desktop/image.png'
start_path = '/Users/cvc/Documents/'

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

print('Relative path: {}'.format(relative_path))

It will print:

Relative path: ../Desktop/image.png

You might also like: