Python os.path.splitdrive() - 将路径名分割成一对驱动器和尾部

Python os.path.splitdrive()

Python中的os.path.splitdrive()方法用于将路径名分割成一对驱动器和尾部。在这里,驱动器要么是一个挂载点,要么是空字符串,而rest路径组件是tail。

在不使用驱动器规范的系统上,驱动器将总是一个空字符串。例子:UNIX。

在Windows上,os.path.splitdrive()方法将给定的路径名分割成驱动器或UNC sharepoint作为驱动器和其他路径组件作为尾巴。
例如:

     path name                         drive                  tail
On Windows
If path contains drive letter
C:\User\Documents\file.txt               C:           C:\User\Documents\file.txt

If the path contains UNC path 
\\host\computer\dir\file.txt       \\host\computer          \dir\file.txt

On Unix
/home/User/Documents/file.txt         {empty}        /home/User/Documents/file.txt   

语法:os.path.splitdrive(path)

参数:

path:表示文件系统路径的类路径对象。类路径对象是表示路径的str或bytes对象。

返回类型:该方法返回一个元组,表示给定路径名的驱动器和尾部。

示例1

使用os.path.splitdrive()方法 (在Windows上)

# Python program to explain os.path.splitdrive() method 
    
# importing os module 
import os
  
# Path Containing a drive letter 
path = R"C:\User\Documents\file.txt"
  
# Split the path in 
# drive and tail pair
drive_tail = os.path.splitdrive(path)
  
# print drive and tail
# of the given path
print("Drive of path '%s:'" %path, drive_tail[0])
print("Tail of path '%s:'" %path, drive_tail[1], "\n")
  
# Path representing a UNC path 
path = R"\\host\computer\dir\file.txt"
  
# Split the path in 
# drive and tail pair
drive_tail = os.path.splitdrive(path)
  
# print drive and tail
# of the given path
print("Drive of path '%s':" %path, drive_tail[0])
print("Tail of path '%s':" %path, drive_tail[1], "\n")
  
# Path representing a relative path 
path = R"\dir\file.txt"
  
# Split the path in 
# drive and tail pair
drive_tail = os.path.splitdrive(path)
  
# print drive and tail
# of the given path
print("Drive of path '%s':" %path, drive_tail[0])
print("Tail of path '%s':" %path, drive_tail[1])

输出:

Drive of path 'C:\User\Documents\file.txt': C:
Tail of path 'C:\User\Documents\file.txt': \User\Documents\file.txt 

Drive of path '\\host\computer\dir\file.txt': \\host\computer 
Tail of path '\\host\computer\dir\file.txt': \dir\file.txt 

Drive of path '\dir\file.txt':  
Tail of path '\dir\file.txt': \dir\file.txt 

示例2

使用os.path.splitdrive()方法(在UNIX上)

# Python program to explain os.path.splitdrive() method 
    
# importing os module 
import os
  
# Path
path = "/home/User/Documents/file.txt"
  
# Split the path in 
# drive and tail pair
drive_tail = os.path.splitdrive(path)
  
# print drive and tail
# of the given path
print("Drive of path '%s':" %path, drive_tail[0])
print("Tail of path '%s':" %path, drive_tail[1])
  
  
# os.path.splitdrive() method
# will return drive as empty everytime
# as UNIX do not use
# drive specification

输出:

Drive of path '/home/User/Documents/file.txt': 
Tail of path '/home/User/Documents/file.txt': /home/User/Documents/file.txt

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程