簡體   English   中英

Python:如何從文件路徑字符串中提取驅動器

[英]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

PathLib 文檔鏈接

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM