Python | os.path.dirname()

Python 中的 OS 模块提供了与操作系统交互的函数。OS 属于 Python 的标准实用程序模块。os.path 模块是 Python 中 OS 模块的子模块,用于常见的路径名操作。

Python 中的 os.path.dirname() 方法用于从指定路径中获取目录名

"""
语法:os.path.dirname(path)
参数:
    path:表示文件系统路径的类路径对象
返回类型:此方法返回一个字符串值,表示指定路径中的目录名
"""

# Python program to explain os.path.dirname() method  
    
# importing os.path module  
import os.path 
  
# Path 
path = '/home/User/Documents'
  
# Get the directory name from the specified path 
dirname = os.path.dirname(path) 
  
# Print the directory name
print(dirname) 
  
  
# Path 
path = '/home/User/Documents/file.txt'

# Get the directory name from the specified path 
dirname = os.path.dirname(path) 
  
# Print the directory name
print(dirname) 

# Path 
path = 'file.txt'
  
# Get the directory name from the specified path 
dirname = os.path.dirname(path) 
  
# Print the directory name
"""
在上述指定路径中不包含任何目录,因此将打印 "无"。
"""
print(dirname) 

测试结果如下:

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值