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
.