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)
测试结果如下: