Python os.path.split()
Python中的os.path.split()方法用于把路径分割成 dirname 和 basename,返回一个元组。在这里,tail是最后一个路径名称组件,head是在此之前的所有内容。
例如,考虑下面的路径名:
path name = '/home/User/Desktop/file.txt'
在上面的例子中,’ file.txt ‘组件的路径名称是尾和’ /home/User/Desktop/ ‘是头.尾部分将永远不包含斜杠;如果路径名以斜杠结束,tail将为空,如果路径名中没有斜杠,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'
语法:os.path.split(path)
参数:
path:表示文件系统路径的类路径对象。类路径对象是表示路径的str或bytes对象。
返回类型:该方法返回一个元组,表示指定路径名的头和尾。
示例1
使用 os.path.split() 方法
# 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
Output:
Head of '': Tail of '':
版权声明:本页面内容旨在传播知识,为用户自行发布,若有侵权等问题请及时与本网联系,我们将第一时间处理。E-mail:284563525@qq.com