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 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





The module os.statvfs is not available on Windows.
see http://docs.python.org/library/os.html#os.statvfs
I wasn’t aware of that, thanks. I never really use windows anymore