Python | os.path.relpath() method
Last Updated :
18 Jun, 2019
OS module in Python provides functions for interacting with the operating system. OS comes under Python’s standard utility modules. This module provides a portable way of using operating system dependent functionality. os.path module is sub module of OS module in Python used for common path name manipulation.
os.path.relpath()
method in Python is used to get a relative filepath to the given path either from the current working directory or from the given directory.
Note: This method only computes the relative path. The existence of the given 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 : Use of os.path.relpath() method
import os
path = "/home / User / Desktop / file.txt"
start = "/home / User"
relative_path = os.path.relpath(path, start)
print (relative_path)
path = "/home / User / Desktop / file.txt"
relative_path = os.path.relpath(path)
print (relative_path)
path = "/home / User / Desktop / file.txt"
start = "GeeksForGeeks / home"
relative_path = os.path.relpath(path, start)
print (relative_path)
path = "/home / User / Desktop / file.txt"
start = "/home / User / ihritik / file.txt"
relative_path = os.path.relpath(path, start)
print (relative_path)
|
Output:
Desktop/file.txt
../User/Desktop/file.txt
../../../User/Desktop/file.txt
../../Desktop/file.txt
Reference: https://docs.python.org/3/library/os.path.html
Share your thoughts in the comments
Please Login to comment...