Python:如何从文件路径字符串中提取驱动器

2024-10-02 10:29:49 发布

您现在位置:Python中文网/ 问答频道 /正文

如果有一个预定义的简单易记的python命令,从mac和windows上都有用的字符串文件路径中提取驱动器号?在

如果MAC:

filepathString = '/Volumes/Some Documents/The Doc.txt'

会导致:

^{pr2}$

如果赢了:

filepathString = 'c:\Some Documents\The Doc.txt'

会导致:

myDrive = 'c:'

Tags: 文件the字符串命令路径txtdocwindows
3条回答

简单示例(Windows):

import os
import pathlib
drive = pathlib.Path(os.getcwd()).parts[0]

我想你必须为此编写自定义代码。使用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]

尝试来自^{}模块的^{}方法和常规的^{}。它不是单行的,但是我还是看不出代码是如何知道将transfer追加到卷路径的,或者检测给定路径是否来自Windows或Unix(记住C:是一个有效的Unix文件名)。在

相关问题 更多 >

    热门问题