从 Python 中的路径确定文件系统类型

Ant*_*rre 6 python filesystems

Python(2.*)中是否有任何可移植的方法来获取包含给定路径的设备的文件系统类型?例如,类似:

>>> get_fs_type("/foo/bar")
'vfat'
Run Code Online (Sandbox Code Playgroud)

Ant*_*rre 3

感谢 user3012759 的评论,这里有一个解决方案(当然可以改进,但仍然有效):

import psutil

def get_fs_type(mypath):
    root_type = ""
    for part in psutil.disk_partitions():
        if part.mountpoint == '/':
            root_type = part.fstype
            continue

        if mypath.startswith(part.mountpoint):
            return part.fstype

    return root_type
Run Code Online (Sandbox Code Playgroud)

GNU/Linux 下需要单独处理“/”,因为所有(绝对)路径都以此开头。

以下是“实际运行”的代码示例(GNU/Linux):

>>> get_fs_type("/tmp")
'ext4'
>>> get_fs_type("/media/WALKMAN")
'vfat'
Run Code Online (Sandbox Code Playgroud)

还有 Windows 下的另一个(如果有的话 XP):

>>> get_fs_type("C:\\")  # careful: "C:" will yield ''
'NTFS'
Run Code Online (Sandbox Code Playgroud)

  • 这不起作用,因为您可能有像这样的嵌套安装: / - root mount; /usr - 其他类型;/usr/tmp - 其他类型;此答案中提供的代码将返回 /usr/tmp/myfile 中文件的 /usr 类型。 (2认同)
  • 对于这种特定情况,唯一有用的“psutil”函数是“disk_partitions”,所以是的:“from psutil import disk_partitions”。 (2认同)