Get hard disk size in Python
Asked Answered
L

6

73

I am trying to get the hard drive size and free space using Python (I am using Python 2.7 with macOS).

I am trying with os.statvfs('/'), especially with the following code. Is it correct what I am doing? Which definition of the variable giga shall I use?

import os

def get_machine_storage():
    result=os.statvfs('/')
    block_size=result.f_frsize
    total_blocks=result.f_blocks
    free_blocks=result.f_bfree
    # giga=1024*1024*1024
    giga=1000*1000*1000
    total_size=total_blocks*block_size/giga
    free_size=free_blocks*block_size/giga
    print('total_size = %s' % total_size)
    print('free_size = %s' % free_size)

get_machine_storage()

EDIT: statvfs is deprecated in Python 3, do you know any alternative?

Landmeier answered 22/2, 2018 at 14:12 Comment(4)
You can take a look here to see how to interpret the output.Tanatanach
@VasilisG. Thanks. I saw that the method is deprecated in Python 3, alternatives?Landmeier
Try using disk_usage from shutil module.Tanatanach
Another question that might be of use to you: #4260616Saintly
T
164

For Python 2 till Python 3.3


Note: As a few people mentioned in the comment section, this solution will work for Python 3.3 and above. For Python 2.7 it is best to use the psutil library, which has a disk_usage function, containing information about total, used and free disk space:

import psutil

hdd = psutil.disk_usage('/')

print ("Total: %d GiB" % hdd.total / (2**30))
print ("Used: %d GiB" % hdd.used / (2**30))
print ("Free: %d GiB" % hdd.free / (2**30))

Python 3.3 and above:

For Python 3.3 and above, you can use the shutil module, which has a disk_usage function, returning a named tuple with the amounts of total, used and free space in your hard drive.

You can call the function as below and get all information about your disk's space:

import shutil

total, used, free = shutil.disk_usage("/")

print("Total: %d GiB" % (total // (2**30)))
print("Used: %d GiB" % (used // (2**30)))
print("Free: %d GiB" % (free // (2**30)))

Output:

Total: 931 GiB
Used: 29 GiB
Free: 902 GiB
Tanatanach answered 22/2, 2018 at 14:24 Comment(6)
Good answer, but only calculates in gigabytes and the sizes of total, used, free could be anything. If you wanted to, you could go as far as using hurry.filesize which automatically handles this :)Gomorrah
@Gomorrah indeed, you 'll have to modify the divisor every time you need different unit. Thanks for the recommendation :)Tanatanach
only since python 3.3Toddtoddie
This gives you the size of a partition, not the whole disk.Anxiety
While solution might work for some, but doesn't work in anything below python 3.3.Xylol
I have 32GB sd card, filesystem erased, it says 8GB ...Aggrandize
S
19

https://pypi.python.org/pypi/psutil

import psutil

obj_Disk = psutil.disk_usage('/')

print (obj_Disk.total / (1024.0 ** 3))
print (obj_Disk.used / (1024.0 ** 3))
print (obj_Disk.free / (1024.0 ** 3))
print (obj_Disk.percent)
Smelser answered 22/2, 2018 at 14:41 Comment(1)
Let me suggest float(1<<30) rather than (1024.0 ** 3)Tyrannicide
G
8

The code is about right, but you're using wrong fields, which may give you the wrong results on a different system. The correct way would be:

>>> os.system('df -k /')
Filesystem     1K-blocks    Used Available Use% Mounted on
/dev/root       14846608 3247272  10945876  23% /

>>> disk = os.statvfs('/')
>>> (disk.f_bavail * disk.f_frsize) / 1024
10945876L
Goerke answered 27/7, 2019 at 6:11 Comment(5)
Does not work on Windows.Yawata
@Yawata OP asked about macOSGoerke
The accepted solution works OS-independentlyYawata
@Yawata the accepted answer gives wrong results compared to os.system('df -k /')Goerke
What are the units?Congener
A
3

Printing out the type can help, when you don't know how to handle a function's result.

print type(os.statvfs('/')) returns <type 'posix.statvfs_result'>

That means it isn't a built in class instance like a string or int..

You can check what you can do with that instance with dir(instance)

print dir(os.statvfs('/')) prints all of it's the properties, functions, variables...

['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmul__', '__setattr__', '__sizeof__',
'__str__', '__subclasshook__', 'f_bavail', 'f_bfree', 'f_blocks',
'f_bsize', 'f_favail', 'f_ffree', 'f_files', 'f_flag', 'f_frsize',
'f_namemax', 'n_fields', 'n_sequence_fields', 'n_unnamed_fields']

By accessing one of the variables, like os.statvfs('/').f_ffree you can extract an integer.

Double check with print type(os.statvfs('/').f_ffree), it does print <type 'int'>.

Additional answered 22/2, 2018 at 14:29 Comment(2)
f_ffree is a number of free file descriptors or something like that, nothing to do with the free space on the driveGoerke
@Goerke No I got it from iterm2.com/python-api/examples/diskspace.html, I didn't see that you had written an actual answer, sorry.Captive
P
0

A one-liner solution to show disk size in GiB based on the answers here:

>>> import shutil

>>> [f"{y}: {x//(2**30)} GiB" for x, y in zip(shutil.disk_usage('/'), shutil.disk_usage('/')._fields)]
['total: 228 GiB', 'used: 14 GiB', 'free: 35 GiB']
Partridge answered 2/6, 2021 at 23:15 Comment(0)
C
0

All the answers in this thread only provide the disk size of the root partition. Here's my code for the people who need complete/entire hard disk size:

total = int()
used  = int()
free  = int()

for disk in psutil.disk_partitions():
    if disk.fstype:
        total += int(psutil.disk_usage(disk.mountpoint).total)
        used  += int(psutil.disk_usage(disk.mountpoint).used)
        free  += int(psutil.disk_usage(disk.mountpoint).free)

print(f'''    
    TOTAL DISK SPACE : {round(total / (1024.0 ** 3), 4)} GiB
    USED DISK SPACE  : {round(used / (1024.0 ** 3), 4)} GiB
    FREE DISK SPACE  : {round(free / (1024.0 ** 3), 4)} GiB
''')
Cordeelia answered 9/5, 2022 at 22:45 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.