Python os.path.relpath()
Python中的os.path.relpath()方法用于从当前工作目录或给定目录获取给定路径的相对文件路径。
注意:此方法只计算相对路径。不检查给定的路径或目录是否存在。
语法:os.path.relpath(path, start =os.curdir)
参数:
path:表示文件系统路径的类路径对象。
start(可选):表示文件系统路径的类路径对象。
给定路径的相对路径将相对于start所指示的目录进行计算。这个参数的默认值是os.curdir,它是操作系统用来引用当前目录的常量字符串。
类路径对象是表示路径的字符串或字节对象。
返回类型:该方法返回一个字符串值,表示从起始目录到给定路径的相对文件路径。
示例1
使用os.path.relpath()方法
# Python program to explain os.path.relpath() method
# importing os module
import os
# Path
path = "/home / User / Desktop / file.txt"
# Path of Start directory
start = "/home / User"
# Compute the relative file path
# to the given path from the
# the given start directory.
relative_path = os.path.relpath(path, start)
# Print the relative file path
# to the given path from the
# the given start directory.
print(relative_path)
# Path
path = "/home / User / Desktop / file.txt"
# Compute the relative file path
# to the given path from the
# the current directory.
# if we do not specify the start
# parameter it will default to
# os.curdir i.e current directory
relative_path = os.path.relpath(path)
# Print the relative file path
# to the given path from the
# the given start directory.
print(relative_path)
# Path
path = "/home / User / Desktop / file.txt"
# Path of Start directory
start = "GeeksForGeeks / home"
# Compute the relative file path
# to the given path from the
# the given start directory.
relative_path = os.path.relpath(path, start)
# Print the relative file path
# to the given path from the
# the given start directory.
print(relative_path)
# Path
path = "/home / User / Desktop / file.txt"
# Path of Start directory
start = "/home / User / ihritik / file.txt"
# Compute the relative file path
# to the given path from the
# the given start directory.
relative_path = os.path.relpath(path, start)
# Print the relative file path
# to the given path from the
# the given start directory.
print(relative_path)
输出:
Desktop/file.txt
../User/Desktop/file.txt
../../../User/Desktop/file.txt
../../Desktop/file.txt