Question

How do I determine if a given path or drive is formatted to EXT4, EXT3, EXT2, FAT32, NTFS or some such, in Python?

Was it helpful?

Solution

psutil is a cross-platform package which can identify partition types:

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

Warning: On linux, the fstype may be reported as ext4 or ntfs, but on Windows, the fstype is limited to "removable", "fixed", "remote", "cdrom", "unmounted" or "ramdisk".

OTHER TIPS

Although it has been a while since the question and answer were posted, I just want to add a little function that you can use to actually find the file system of a given path. The answer extends unutbu's answer.
The answer is also quite useful for macOS users, where it is not possible to print the file system with df -T (also at my machine df --print-type did also not work). See the man page for more information (it suggests using the lsvfs command to display the available file systems).

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

(tested on macOS and linux)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top