Python: diskspace

I wanted a simple function to use in a program I am writing to ensure that the disk isn’t getting full, after a quick search I found a blog post on with a great solution:

# os module required
import os

# retrieves information for the harddrive where root is mounted
# in windows replace this with "C:\" or the relevant drive letter
disk = os.statvfs("/")

# Information is recieved in numbers of blocks free
# so we need to multiply by the block size to get the space free in bytes
capacity = disk.f_bsize * disk.f_blocks
available = disk.f_bsize * disk.f_bavail
used = disk.f_bsize * (disk.f_blocks - disk.f_bavail) 

# print information in bytes
print used, available, capacity

# print information in Kilobytes
print used/1024, available/1024, capacity/1024

# print information in Megabytes
print used/1.048576e6, available/1.048576e6, capacity/1.048576e6

# print information in Gigabytes
print used/1.073741824e9, available/1.073741824e9, capacity/1.073741824e9

You can argue about if they should be KiB or KB if you want, but i take them as 1024 bytes in a kilobyte


  1. Christian

    The module os.statvfs is not available on Windows.

  2. mat

    I wasn’t aware of that, thanks. I never really use windows anymore 🙂

  3. […] viewer, part 1 Posted on August 19, 2010 by bjornr64 Here’s some code I got from I know that the result is not precise but for my use it’s ok. (For more info about Megabytes […]

  4. Paulo Junior

    Hi, this article was a lot of helpful. Thanks.

Leave a Comment

Your email address will not be published. Required fields are marked *