python in os.path.split () function usage

basic concepts

The os.path.split () divided by the path name of the one pair of the head and tail of the list. Yes tail of the list of last pathname elements. head element is in front of it.

for example:

path name = '/home/User/Desktop/file.txt'

In the above example, the path name is called tail file.txt path '/ home / User / Desktop / ' called the head. tail part will never contain a slash symbol. If this path name ends with a slash, then the tail is empty.
If there is no slash in the path, then the head is empty. Here are the detailed parameters:

    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'

Case Analysis

1 Example one:

# 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 results:

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

Examples of two 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 Test results:

Head of '': 
Tail of '':
Published 706 original articles · won praise 829 · Views 1.32 million +

Guess you like

Origin blog.csdn.net/sinat_38682860/article/details/105125313