Python:如何从文件路径字符串中提取驱动器
是否有一个预定义的单行易于记忆的python命令,可以从mac和windows上都有用的字符串文件路径中提取驱动器号 如果MAC:Python:如何从文件路径字符串中提取驱动器,python,string,split,Python,String,Split,是否有一个预定义的单行易于记忆的python命令,可以从mac和windows上都有用的字符串文件路径中提取驱动器号 如果MAC: filepathString = '/Volumes/Some Documents/The Doc.txt' 将导致: myDrive = '/Volumes/transfer' myDrive = 'c:' 如果获胜: filepathString = 'c:\Some Documents\The Doc.txt' 将导致: myDrive = '/Vol
filepathString = '/Volumes/Some Documents/The Doc.txt'
将导致:
myDrive = '/Volumes/transfer'
myDrive = 'c:'
如果获胜:
filepathString = 'c:\Some Documents\The Doc.txt'
将导致:
myDrive = '/Volumes/transfer'
myDrive = 'c:'
尝试模块中的方法和常规方法。这不是一行,但我不知道代码如何知道如何将
transfer
附加到卷路径,或者检测给定路径是否来自Windows或Unix(请记住C:
是有效的Unix文件名)。我想您必须为此编写自定义代码。使用platform.system()
或platform.uname()
草图:
def volume_name(path):
if platform.system() == "Darwin":
return re.search("^\/Volumes\/[^/]+/", path).group(0)
elif platform.system() == "Windows":
return path[0:2]
简单示例(Windows):