Python中的OS模块提供了与操作系统进行交互的函数。操作系统属于Python的标准实用程序模块。该模块提供了使用依赖于操作系统的函数的便携式方法。 os.path模块是Python中OS模块的子模块,用于通用路径名操作。
os.path.relpath()
Python中的方法用于从当前工作目录或给定目录获取到给定路径的相对文件路径。
注意:此方法仅计算相对路径。不检查给定路径或目录的存在。
用法: os.path.relpath(path, start = os.curdir)
参数:
path:代表文件系统路径的path-like对象。
start(可选):代表文件系统路径的path-like对象。
给定路径的相对路径将相对于start指示的目录进行计算。此参数的默认值为os.curdir,它是操作系统用来引用当前目录的常量字符串。
path-like对象是表示路径的字符串或字节对象。
返回类型:此方法返回一个字符串值,该字符串值表示从起始目录到给定路径的相对文件路径。
代码:使用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
参考: https://docs.python.org/3/library/os.path.html
相关用法
- Python os.dup()用法及代码示例
- Python next()用法及代码示例
- Python set()用法及代码示例
- Python object()用法及代码示例
- Python bytes()用法及代码示例
- Python os.times()用法及代码示例
- Python os.chmod用法及代码示例
- Python hash()用法及代码示例
- Python os.ftruncate()用法及代码示例
- Python os.truncate()用法及代码示例
- Python os.fsdecode()用法及代码示例
- Python dict pop()用法及代码示例
- Python os.abort()用法及代码示例
- Python os.WEXITSTATUS()用法及代码示例
注:本文由纯净天空筛选整理自ihritik大神的英文原创作品 Python | os.path.relpath() method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。