Python os.path.dirname()
Python中的os.path.dirname()方法用于从指定的路径获取目录名。
语法:os.path.dirname(path)
参数:
path:表示文件系统路径的类路径对象。
返回类型:该方法返回一个字符串值,表示指定路径中的目录名。
示例1
使用os.path.dirname()方法
# 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)
# In the above specified path
# does not contains any
# directory so,
# It will print Nothing
输出:
/home/User
/home/User/Documents