Python os.path.relpath() Method



The Python os.path.relpath() method is used to retrieve the relative path from one specified path to another. The method calculates the relative path between a starting path and a target path based on the current working directory or a specified start directory.

If the starting and ending paths are the same, the method returns an empty string. If the starting path is not an ancestor of the ending path, it raises a "ValueError".

Syntax

Following is the basic syntax of the Python os.path.relpath() method −

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

Parameter

This method accepts the following parameters −

  • path − This is a string representing the path to get the relative filepath for.

  • start (optional) − It represents the start directory to calculate the relative path from. If not provided, it defaults to the current directory (os.curdir).

Return Value

The method returns a string representing the relative filepath to the specified start directory. If start is not provided, the relative filepath is calculated from the current directory.

Example

In the following example, we are calculating the relative path from "/path/to/dir" to "/path/to/dir/file.txt" using the relpath() method −

import os
path1 = "/path/to/dir"
path2 = "/path/to/dir/file.txt"
relative_path = os.path.relpath(path2, path1)
print(relative_path)  

Output

Since "file.txt" is located directly within "dir", the relative path is simply 'file.txt' as shown in the output below −

file.txt

Example

Here, we are calculating the relative path from "/path/to/dir1" to "/path/to/dir2/file.txt" −

import os
path1 = "/path/to/dir1"
path2 = "/path/to/dir2/file.txt"
relative_path = os.path.relpath(path2, path1)
print(relative_path) 

Output

Since "file.txt" is located in a different parent directory, the relative path includes '../dir2/file.txt' as shown in the output below −

../dir2/file.txt

Example

This example calculates the relative path from the current working directory to "/path/to/file.txt" −

import os
current_dir = os.getcwd()
file_path = "/path/to/file.txt"
relative_path = os.path.relpath(file_path, current_dir)
print(relative_path)  

Output

We get the output as shown below −

../../../../path/to/file.txt 

Example

Now, we are calculating the relative path from an empty path to "file.txt". Since one of the paths is empty, the method returns the non-empty path as the result −

import os
path1 = ""
path2 = "file.txt"
relative_path = os.path.relpath(path2, path1)
print(relative_path)  

Output

The result produced is as follows −

file.txt
os_path_methods.htm
Advertisements