Skip to content

Instantly share code, notes, and snippets.

@jordan-carson
Last active November 2, 2019 19:32
Show Gist options
  • Save jordan-carson/b2f12804fb965f102136f089d5911bb0 to your computer and use it in GitHub Desktop.
Save jordan-carson/b2f12804fb965f102136f089d5911bb0 to your computer and use it in GitHub Desktop.
Readable Disk Space Usage in Python
import os
import collections
_ntuple_diskusage = collections.namedtuple('usage', 'total used free')
__doc__ = """
Function to return the disk usage for a given path. Works for both Windows & Linux/MaxOS systems.
Returns:
Named Tuple: (usage.total, usage.used, usage.free)
"""
if hasattr(os, 'statvfs'): # POSIX
def disk_usage(path):
st = os.statvfs(path)
free = st.f_bavail * st.f_frsize
total = st.f_blocks * st.f_frsize
used = (st.f_blocks - st.f_bfree) * st.f_frsize
return _ntuple_diskusage(total, used, free)
elif os.name == 'nt': # Windows
import ctypes
import sys
def disk_usage(path):
_, total, free = ctypes.c_ulonglong(), ctypes.c_ulonglong(), \
ctypes.c_ulonglong()
if sys.version_info >= (3,) or isinstance(path, unicode):
fun = ctypes.windll.kernel32.GetDiskFreeSpaceExW
else:
fun = ctypes.windll.kernel32.GetDiskFreeSpaceExA
ret = fun(path, ctypes.byref(_), ctypes.byref(total), ctypes.byref(free))
if ret == 0:
raise ctypes.WinError()
used = total.value - free.value
return _ntuple_diskusage(total.value, used, free.value)
else:
raise NotImplementedError("platform not supported")
def bytes2human(n):
symbols = ('K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y')
prefix = {}
for i, s in enumerate(symbols):
prefix[s] = 1 << (i+1)*10
for s in reversed(symbols):
if n >= prefix[s]:
value = float(n) / prefix[s]
return '%.1f%s' % (value, s)
return "%sB" % n
disk_usage.__doc__ = __doc__
if __name__ == '__main__':
print(__doc__)
usage = disk_usage(os.path.pardir)
human_dict = dict()
for name, amt in dict(usage._asdict()).items():
human_dict[name] = bytes2human(amt)
print(human_dict)
@jordan-carson
Copy link
Author

Updated to return by default 'pardir' which equates to '..'.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment