Spread Firefox Affiliate Button

Pages

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.

7 comments to Getting free diskspace in python

  • Hey, thanks for this, I’d been using BFREE, and couldn’t figure out why I was getting inaccurate readings.

  • This was just what I was looking for. Thanks!

  • Sébastien Grenier

    Thanks a lot! I’m new to python and I’m not a programmer, this piece of code save me time and it’s only 4 lines!

    Thank again!

  • JT

    Thanks a fourth time, your google ranking is high ;)

  • Perfect, I am going to use this to fix purge_builds.py from mozilla bug 512199

  • Dan Aquinas

    Be warned that ’statvfs’ is only available on UNIX.
    Trying this code with Python 2.5 on Windows XP + SP3 yields following error:

    AttributeError: ‘module’ object has no attribute ’statvfs’

  • tanks!!.

    I thought solution the problem with a system call with the df command in linux with the command df, ‘;¬( but your solution is more elegant, does it work for all operating systems?(I mention this for what it says Dan Aquinas).
    I think that the function will return the space in mega bytes would be:

    import os
    def freespace(p):
    “”"
    Returns the number of free MegaBytes on the drive that “p“ is on
    “”"
    s = os.statvfs(p)
    return (s.f_bsize * s.f_bavail)/(1024*1024)

Leave a Reply

 

 

 

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">