如何获取目录或驱动器的文件系统?
我想知道怎么用Python来判断一个路径或者驱动器是格式化成EXT4、EXT3、EXT2、FAT32、NTFS还是其他格式的?
2 个回答
1
虽然这个问题和答案已经发布了一段时间,但我想补充一个小功能,帮助你找到给定路径的文件系统。这个答案是对unutbu的回答的扩展。
这个答案对macOS用户也很有用,因为在macOS上无法使用df -T
命令打印文件系统(我机器上的df --print-type
也不管用)。想了解更多信息,可以查看手册页(它建议使用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上测试过)
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系统上,分区类型可能会显示为 ext4
或 ntfs
,而在Windows系统上,分区类型则只会显示为 "removable"(可移动的)、"fixed"(固定的)、"remote"(远程的)、"cdrom"(光盘)、"unmounted"(未挂载的)或 "ramdisk"(虚拟内存盘)
。