基本コンセプト
リストの頭部と尾部の一対のパス名で割っos.path.split()。はい、最後のパス名の要素のリストの末尾。head要素は、その前にあります。
例えば:
path name = '/home/User/Desktop/file.txt'
上記の例では、パス名は、テールfile.txtをパス「/ホーム/ユーザー/デスクトップ/と呼ばれる 」 ヘッドと呼ばれます。テール部分はスラッシュ記号が含まれることはありません。このパス名がスラッシュで終わる場合、テールは空です。
パスにはスラッシュがない場合、ヘッドは空です。ここでは詳細なパラメータは以下のとおりです。
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'
ケーススタディ
1例1:
# 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")
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 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])
2つの結果:
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 3の例
# Python program to explain os.path.split() method
'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:579817333
寻找有志同道合的小伙伴,互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
# 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
4つの試験結果:
Head of '':
Tail of '':