Python os.path.basename()
Python os.path.basename() 方法用于获取指定路径中的基名称。本方法内部使用 os.path.split() 方法将指定的路径分割为一个pair(head, tail)
os.path.basename() 方法将指定路径拆分为 pair(head, tail)
语法: os.path.basename(path)
参数:
path:表示文件系统路径的类路径对象。
返回类型: 此方法返回一个字符串值,该值表示指定路径的基名称。
示例1
使用 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 splitted 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 splitted 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