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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。