如何获取目录或驱动器的文件系统?

4

在Python中,如何确定给定的路径或驱动器是否格式化为EXT4、EXT3、EXT2、FAT32、NTFS或类似格式?


2个回答

6

psutil 是一个跨平台的包,可以识别分区类型

>>> psutil.disk_partitions()
[sdiskpart(device='/dev/sda1', mountpoint='/', fstype='ext4', opts='rw,nosuid'),
 sdiskpart(device='/dev/sda2', mountpoint='/home', fstype='ext4', opts='rw')]

警告:在Linux上,fstype可能报告为ext4ntfs,但是在Windows上,fstype限制为"removable"、"fixed"、"remote"、"cdrom"、"unmounted"或"ramdisk"


太棒了,谢谢。如果有一种方法可以找出特定目录的文件系统,那将是你答案的一个很好的补充。不过这也已经很有帮助了。 - Brōtsyorfuzthrāx
3
在Linux上,你可以尝试解析df -TP path的输出,但这样做可能会非常棘手,因为设备名称和挂载点可能包含空格。 - unutbu
看起来现在你可以在Windows上获取实际的fstype,所以你之前的警告现在是“无效”的。我可以确认它有效,但也请查看psutil的提交消息:https://github.com/giampaolo/psutil/issues/209#issuecomment-44019539 - Patrick

1
虽然发布问题和回答已经有一段时间了,但我只是想增加一个小功能,让你可以找到给定路径的文件系统。这个回答基于unutbu's answer进行扩展。
对于使用 macOS 的用户来说,这个答案也非常有用,在 macOS 上无法使用 df -T 命令来打印文件系统(在我的机器上,df --print-type 也不起作用)。请参阅 man page 获取更多信息(它建议使用 lsvfs 命令显示可用的文件系统)。
import psutil
import os

def extract_fstype(path_=os.getcwd()):
    """Extracts the file system type of a given path by finding the mountpoint of the path."""
    for i in psutil.disk_partitions(all=True):
        if path_.startswith(i.mountpoint):
            
            if i.mountpoint == '/':  # root directory will always be found
                # print(i.mountpoint, i.fstype, 'last resort')  # verbose
                last_resort = i.fstype
                continue
            
            # print(i.mountpoint, i.fstype, 'return')  # verbose
            return i.fstype

    return last_resort

(在 macOS 和 Linux 上测试过)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接