Skip to content

Python: diskspace

by mat on September 3rd, 2009

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 permalink

    The module os.statvfs is not available on Windows.

  2. I wasn’t aware of that, thanks. I never really use windows anymore :)

  3. Paulo Junior permalink

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

Trackbacks & Pingbacks

  1. Python – harddrive usage viewer, part 1 | Bjornr64's Blog

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS