Welcome, guest | Sign In | My Account | Store | Cart
#!/usr/bin/env python

"""
Return disk usage statistics about the given path as a (total, used, free)
namedtuple.  Values are expressed in bytes.
"""
# Author: Giampaolo Rodola' <g.rodola [AT] gmail [DOT] com>
# License: MIT

import os
import collections

_ntuple_diskusage = collections.namedtuple('usage', 'total used 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
    def disk_usage(path):
        from ctypes import c_ulong, byref, windll, WinError
        _, total, free = c_ulong(), c_ulong(), c_ulong()
        ret = windll.kernel32.GetDiskFreeSpaceExA(path, byref(_), byref(total),
                                                  byref(free))
        if ret == 0:
            raise WinError()
        used = total.value - free.value
        return _ntuple_diskusage(total.value, used, free.value)
else:
    raise NotImplementedError("platform not supported")

disk_usage.__doc__ = __doc__


if __name__ == '__main__':
    print disk_usage(os.getcwd())

History