Python| os.path.split() 方法
Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。
Python中的os.path.split()
方法用于将路径名拆分为一对head和tail 。在这里, tail是最后一个路径名组件,而head是通往该路径的所有内容。
例如,考虑以下路径名:
path name = '/home/User/Desktop/file.txt'
在上面的例子中,路径名的'file.txt'组件是tail , '/home/User/Desktop/'是head。尾部永远不会包含斜杠;如果路径名以斜杠结尾,则尾部为空,如果路径名中没有斜杠,则头部为空。
例如:
path head tail
'/home/user/Desktop/file.txt' '/home/user/Desktop/' 'file.txt'
'/home/user/Desktop/' '/home/user/Desktop/' {empty}
'file.txt' {empty} 'file.txt'
Syntax: os.path.split(path)
Parameter:
path: A path-like object representing a file system path. A path-like object is either a str or bytes object representing a path.
Return Type: This method returns a tuple that represents head and tail of the specified path name.
# Python program to explain os.path.split() method
# importing os module
import os
# path
path = '/home/User/Desktop/file.txt'
# Split the path in
# head and tail pair
head_tail = os.path.split(path)
# print head and tail
# of the specified path
print("Head of '% s:'" % path, head_tail[0])
print("Tail of '% s:'" % path, head_tail[1], "\n")
# path
path = '/home/User/Desktop/'
# Split the path in
# head and tail pair
head_tail = os.path.split(path)
# print head and tail
# of the specified path
print("Head of '% s:'" % path, head_tail[0])
print("Tail of '% s:'" % path, head_tail[1], "\n")
# path
path = 'file.txt'
# Split the path in
# head and tail pair
head_tail = os.path.split(path)
# print head and tail
# of the specified path
print("Head of '% s:'" % path, head_tail[0])
print("Tail of '% s:'" % path, head_tail[1])
Head of '/home/User/Desktop/file.txt': /home/User/Desktop
Tail of '/home/User/Desktop/file.txt': file.txt
Head of '/home/User/Desktop/': /home/User/Desktop
Tail of '/home/User/Desktop/':
Head of 'file.txt':
Tail of 'file.txt': file.txt
代码 #2:如果路径为空
# Python program to explain os.path.split() method
# importing os module
import os
# path
path = ''
# Split the path in
# head and tail pair
head_tail = os.path.split(path)
# print head and tail
# of the specified path
print("Head of '% s':" % path, head_tail[0])
print("Tail of '% s':" % path, head_tail[1])
# os.path.split() function
# will return empty
# head and tail if
# specified path is empty
Head of '':
Tail of '':
参考: https://docs。 Python.org/3/library/os.path.html