Get hard disk size in Python

前端 未结 4 1015
闹比i
闹比i 2020-12-23 20:01

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

4条回答
  •  春和景丽
    2020-12-23 20:22

    For Python 2 till Python 3.3


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

    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
    

提交回复
热议问题