Python| os.path.dirname() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.dirname()
方法用于从指定路径获取目录名。
Syntax: os.path.dirname(path)
Parameter:
path: A path-like object representing a file system path.
Return Type: This method returns a string value which represents the directory name from the specified path.
代码:使用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
参考: https://docs。 Python.org/3/library/os.path.html