In this tutorial, we will introduce how to get disk or directory total space, used space and free space using python, which is very helpful if you want to save some files on you computer.
Get total, used and free space information
The disk usage information is:
usage(total=128857235456, used=113601175552, free=15256059904)
As to shutil.disk_usage() function.
On windows, path must be a directory; on unix, it can be a file or directory.
Meanwhile, the disk usage information is not user friendly, we can format it.
Format disk usage
def formatSize(bytes): try: bytes = float(bytes) kb = bytes / 1024 except: return "Error" if kb >= 1024: M = kb / 1024 if M >= 1024: G = M / 1024 return "%.2fG" % (G) else: return "%.2fM" % (M) else: return "%.2fkb" % (kb)
As to free space, we can get it like this:
usage = shutil.disk_usage("F:\\") free_space = formatSize(usage) print(free_space)
The free space is: 14.21G
Of course, you also can use other way to get disk free space, you can read this tutorial.