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.

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!
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!
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
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)
Thank you!
If you are attempting to do this in THE MOST USED OPERATING SYSTEM IN THE WORLD…
You are out of luck. This doesn’t work and no one knows what the alternative is.
@jaja, there is a solution actually: http://stackoverflow.com/questions/51658/cross-platform-space-remaining-on-volume-using-python
The operating system you mention is not made to program on, though. It is a console game platform.
@jaja
Only the most used operating system ON PERSONAL COMPUTERS
(I can use caps too
)
The most common operating system in the world is by far and away linux, when considering the millions of web servers and app servers. That’s ignoring the millions of unix based mobile devices.
Thanks btw, exactly what I was looking for!