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 wi
Notice: 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))
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
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
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'>
.
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)