Skip to main content

Getting free diskspace in python

To calculate the amount of free disk space in Python, you can use the os.stafvfs() function. For some reason, I can never find the docs for os.statvfs() on the first or second try (it's in the "Files and Directories" section in the os module), and I never remember how it works, so I'm posting this as a note to myself, and maybe to help out anybody else wanting to do the same thing. A simple free space function can be written as:

import os

def freespace(p):
    """
    Returns the number of free bytes on the drive that ``p`` is on
    """
    s = os.statvfs(p)
    return s.f_bsize * s.f_bavail
I use the f_bavail attribute instead of f_bfree, since the latter includes blocks that are reserved for the the super-user's use. I'm not sure, however, on the distinction between f_bsize and f_frsize.

Comments