简体   繁体   中英

Get name and size for each hard drive partition

I have written code which lists me all drive letters used on my PC. How can I get the name, the total size, the free space and the already used space of each of these drives? (I am using Python 3.7)

My code:

import os
import string

drives = ['%s:' % drive + '\\' for drive in string.ascii_uppercase if os.path.exists('%s:' % drive)]

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.

import shutil

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

print("Total: %d GiB" % (total // (2**30))

You can use psutil module to get the partition information as well.
You have to install the module ( pip install psutil )
Once you get the partition information you can use disk_usage function, which is running the same script as shutil module to get the spcae information of each partition.

import psutil

for disk in psutil.disk_partitions():
    if disk.fstype:
        print(disk.device, psutil.disk_usage(disk.mountpoint))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM