Cross-platform space remaining on volume using python Cross-platform space remaining on volume using python windows windows

Cross-platform space remaining on volume using python


import ctypesimport osimport platformimport sysdef get_free_space_mb(dirname):    """Return folder/drive free space (in megabytes)."""    if platform.system() == 'Windows':        free_bytes = ctypes.c_ulonglong(0)        ctypes.windll.kernel32.GetDiskFreeSpaceExW(ctypes.c_wchar_p(dirname), None, None, ctypes.pointer(free_bytes))        return free_bytes.value / 1024 / 1024    else:        st = os.statvfs(dirname)        return st.f_bavail * st.f_frsize / 1024 / 1024

Note that you must pass a directory name for GetDiskFreeSpaceEx() to work(statvfs() works on both files and directories). You can get a directory namefrom a file with os.path.dirname().

Also see the documentation for os.statvfs() and GetDiskFreeSpaceEx.


Install psutil using pip install psutil. Then you can get the amount of free space in bytes using:

import psutilprint(psutil.disk_usage(".").free)


You could use the wmi module for windows and os.statvfs for unix

for window

import wmic = wmi.WMI ()for d in c.Win32_LogicalDisk():    print( d.Caption, d.FreeSpace, d.Size, d.DriveType)

for unix or linux

from os import statvfsstatvfs(path)