Home > python > Python: diskspace

Python: diskspace

September 3rd, 2009 mat Leave a comment Go to comments

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 thinkhole.org 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

Bookmark and Share
Categories: python Tags:
  1. Christian
    April 13th, 2010 at 08:49 | #1

    The module os.statvfs is not available on Windows.
    see http://docs.python.org/library/os.html#os.statvfs

  2. April 13th, 2010 at 16:24 | #2

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

  1. August 19th, 2010 at 13:37 | #1
// unused langs // // // //