Python中的OS模塊提供了與操作係統進行交互的函數。操作係統屬於Python的標準實用程序模塊。該模塊提供了使用依賴於操作係統的函數的便攜式方法。 os.path模塊是Python中OS模塊的子模塊,用於通用路徑名操作。
os.path.basename()
Python中的方法用於獲取指定路徑中的基本名稱。此方法在內部使用os.path.split()方法將指定路徑分為一對(頭,尾)。os.path.basename()
方法將指定的路徑拆分為後返回尾部(頭,尾)對。
用法: os.path.basename(path)
參數:
path:代表文件係統路徑的path-like對象。
返回類型:此方法返回一個字符串值,該字符串值表示指定路徑的基本名稱。
代碼:用於os.path.basename()
方法
# Python program to explain os.path.basename() method
# importing os.path module
import os.path
# Path
path = '/home/User/Documents'
# Above specified path
# will be splited into
# (head, tail) pair as
# ('/home/User', 'Documents')
# Get the base name
# of the specified path
basename = os.path.basename(path)
# Print the base name
print(basename)
# Path
path = '/home/User/Documents/file.txt'
# Above specified path
# will be splited into
# (head, tail) pair as
# ('/home/User/Documents', 'file.txt')
# Get the base name
# of the specified path
basename = os.path.basename(path)
# Print the basename name
print(basename)
# Path
path = 'file.txt'
# The above specified path
# will be splitted into
# head and tail pair
# as ('', 'file.txt')
# so 'file.txt' will be printed
# Get the base name
# of the specified path
basename = os.path.basename(path)
# Print the base name
print(basename)
輸出:
Documents file.txt file.txt
參考: https://docs.python.org/3/library/os.path.html
相關用法
- Python next()用法及代碼示例
- Python os.dup()用法及代碼示例
- Python set()用法及代碼示例
- Python Decimal max()用法及代碼示例
- Python PIL ImageOps.fit()用法及代碼示例
- Python os.rmdir()用法及代碼示例
- Python sympy.det()用法及代碼示例
- Python Decimal min()用法及代碼示例
- Python os.readlink()用法及代碼示例
- Python os.writev()用法及代碼示例
- Python os.readv()用法及代碼示例
- Python PIL RankFilter()用法及代碼示例
- Python os.rename()用法及代碼示例
- Python os.sendfile()用法及代碼示例
注:本文由純淨天空篩選整理自ihritik大神的英文原創作品 Python | os.path.basename() method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。