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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
