簡體   English   中英

在Python中,如何獲取給定文件路徑的文件系統

[英]In Python, how can I get the file system of a given file path

在python中,給定像/ usr / local這樣的目錄或文件路徑,我需要獲取其可用的文件系統。 在某些系統中,它可能是/(root)本身,而在其他系統中它可能是/ usr。

我試過os.statvfs它沒有幫助。 我是否必須使用路徑名運行df命令並從輸出中提取文件系統? 有更好的解決方案嗎?

它僅適用於linux / unix平台。

謝謝

這是這里找到的配方的略微修改版本。 添加了os.path.realpath ,因此正確處理了符號鏈接。

import os
def getmount(path):        
    path = os.path.realpath(os.path.abspath(path))
    while path != os.path.sep:
        if os.path.ismount(path):
            return path
        path = os.path.abspath(os.path.join(path, os.pardir))
    return path

使用os.stat獲取有問題的文件/目錄的設備號( st_dev字段),然后遍歷系統掛載( /etc/mtab/proc/mounts ),將每個掛載點的st_dev與此數字進行比較。

df本身打開並解析/etc/mtab ,您可以采用這種方式解析此文件(另一種方法是/proc/mounts ),或者您確實解析了df輸出。

暫無
暫無

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

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