Python | os.path.relpath () method

Python Methods and Functions

os.path.relpath() in Python is used to get the relative path to a file at a given path from either the current working directory or from the given directory.

Note. This method only computes the relative path. The existence of the specified path or directory is not checked.

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

Parameter:
path : A path-like object representing the file system path.
start (optional): A path-like object representing the file system path.
The relative path for given path will be computed with respect to the directory indicated by start. The default value of this parameter is os.curdir which is a constant string used by the operating system to refer to the current directory.

A path-like object is either a string or bytes object representing a path.

Return Type: This method returns a string value which represents the relative file path to given path from the start directory.

Code: using the os.path.relpath () method

# Python program to explain the os.path.relpath () method

 
# import of the os module

import os

 
# Path

path = "/ home / User / Desktop / file.txt"

 
# Path to starting directory

start = "/ home / User"

 
# Calculate the relative path to the file
# to the specified path from
# this starting directory.

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

 
# Print relative file path
# to the specified path from
# this starting directory.

print (relative_path)

 

 

 
# Path

path = "/ home / User / Desktop / file.txt"

 
# Calculate the relative path to the file
# to the specified path from
# current directory.

 
# if we do not specify the beginning
# default parameter
# os.curdir etc. e. current directory

relative_path = os.path .relpath (path)

 
# Print the relative path to the file
# to the specified path from
# this starting directory.

print (relative_path)

 

 
# Path

path = "/ home / User / Desktop / file.txt"

 
# Path to the starting directory

start = "GeeksForGeeks / home"

  
# Calculate the relative path to the file
# to the specified path from
# given starting directory.

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

  
# Print the relative path to the file
# to the specified path from
# given starting directory.

print (relative_path)

 

 
# Path

path = "/ home / User / Desktop / file.txt "

  
# Path to the starting directory

start = "/ home / User / ihritik / file.txt"

  
# Calculate the relative path to the file
# to the specified path from
# given starting directory.

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

 
# Print the relative path to the file
# to the specified path from
# this starting directory.

print (relative_path)

Exit:

 Desktop / file.txt ../User/Desktop/file.txt ../../../User/Desktop/file.txt ../../Desktop/file.txt 

Link: https://docs.python.org/3/ library / os.path.html





Tutorials