[英]Python: How to extract Drive from Filepath string
If there a pre-defined single-line easy to remember python command that extracts a drive letter from a string filepath useful on both mac and windows?如果有一个预定义的单行易于记忆的 python 命令,它从一个在 mac 和 windows 上都有用的字符串文件路径中提取一个驱动器号?
if MAC:如果 MAC:
filepathString = '/Volumes/Some Documents/The Doc.txt'
would result to :将导致:
myDrive = '/Volumes/transfer'
if WIN:如果获胜:
filepathString = 'c:\Some Documents\The Doc.txt'
would result to :将导致:
myDrive = 'c:'
Try the splitdrive
method from the os.path
module along with the regular split
. 尝试使用
os.path
模块中的splitdrive
方法以及常规split
。 It's not single line, but then again I can't see how the code would know to append transfer
to the volume path, or detect if a given path is from Windows or Unix (remember C:
is a valid Unix filename). 它不是一行,但是我再也看不到代码如何知道将
transfer
追加到卷路径,或者检测给定路径是来自Windows还是Unix(记住C:
是有效的Unix文件名)。
I think you're going to have to write custom code for this. 我认为您将不得不为此编写自定义代码。 Use
platform.system()
or platform.uname()
to find out what kind of system you're on, then use os.path
functions to extract the drive/volume name in a way appropriate to the detected platform. 使用
platform.system()
或platform.uname()
来确定您所使用的系统,然后使用os.path
函数以适合于检测到的平台的方式提取驱动器/卷的名称。
A sketch: 草图:
def volume_name(path):
if platform.system() == "Darwin":
return re.search("^\/Volumes\/[^/]+/", path).group(0)
elif platform.system() == "Windows":
return path[0:2]
Simple example(Windows): 简单示例(Windows):
import os
import pathlib
drive = pathlib.Path(os.getcwd()).parts[0]
Pathlib now has a property drive
which makes this really easy by calling path.drive
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.