📜  Python| os.path.splitdrive() 方法

📅  最后修改于: 2022-05-13 01:54:25.177000             🧑  作者: Mango

Python| os.path.splitdrive() 方法

Python中的OS 模块提供了与操作系统交互的功能。操作系统属于 Python 的标准实用程序模块。该模块提供了一种使用操作系统相关功能的可移植方式。 os.path模块是Python中OS 模块的子模块,用于常见的路径名操作。

Python中的os.path.splitdrive()方法用于将路径名拆分为一对drivetail 。在这里, drive是挂载点或空字符串,其余路径组件是tail

在不使用驱动器规范的系统上,驱动器将始终为空字符串。示例:UNIX。

在 Windows 上, os.path.splitdrive()方法将给定的路径名称拆分为 drive 或 UNC sharepoint 作为drive和其他路径组件作为tail
例如:

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   
代码 #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

参考: https://docs。 Python.org/3/library/os.path.html