[英]Python: How to extract Drive from Filepath string
如果有一个预定义的单行易于记忆的 python 命令,它从一个在 mac 和 windows 上都有用的字符串文件路径中提取一个驱动器号?
如果 MAC:
filepathString = '/Volumes/Some Documents/The Doc.txt'
将导致:
myDrive = '/Volumes/transfer'
如果获胜:
filepathString = 'c:\Some Documents\The Doc.txt'
将导致:
myDrive = 'c:'
尝试使用os.path
模块中的splitdrive
方法以及常规split
。 它不是一行,但是我再也看不到代码如何知道将transfer
追加到卷路径,或者检测给定路径是来自Windows还是Unix(记住C:
是有效的Unix文件名)。
我认为您将不得不为此编写自定义代码。 使用platform.system()
或platform.uname()
来确定您所使用的系统,然后使用os.path
函数以适合于检测到的平台的方式提取驱动器/卷的名称。
草图:
def volume_name(path):
if platform.system() == "Darwin":
return re.search("^\/Volumes\/[^/]+/", path).group(0)
elif platform.system() == "Windows":
return path[0:2]
简单示例(Windows):
import os
import pathlib
drive = pathlib.Path(os.getcwd()).parts[0]
Pathlib 现在有一个属性drive
,通过调用path.drive
使这变得非常容易
from pathlib import Path
path = Path(r'F:\\test\folder\file.txt')
path.drive
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.