分区磁盘python

Partition disk python

我想获取所有本地磁盘及其分区,结果 return 所有数据 "total space, used space and free space"。问题是检查分区是否存在,如果不存在则通过错误继续结束。

在下面的代码中,我的本地磁盘有三个分区:C:\, D:\, F:\。但是,分区 G:\ 不存在,因此挂起然后关闭。

我正在使用 Python 3.6 和 Pycharm 社区。

def disk_usage(self):
        disks = ['C','D','F','G']
        for i in disks:
            total, used, free = shutil.disk_usage(i+":\")
            try:
                print("Drive " + i + " as follows:")
                print("==================")
                print("Total: %d GB" % (total // (2**30)))
                print("Used: %d GB" % (used // (2**30)))
                print("Free: %d GB" % (free // (2**30)))
                print("===========")
                print("")
            except GetoptError as err:
               print(err)

提前致谢,

你可以在计算大小之前查看路径是否存在:

p = i+":"+os.sep
if os.path.exists(p):
    total, used, free = shutil.disk_usage(p)

或者捕获 OSError 异常

try:
   total, used, free = shutil.disk_usage(i+":\")
   ...
catch OSError:
    pass

顺便说一句,最好也动态获取该驱动器列表(参见 Is there a way to list all the available drive letters in python?)。

这可能仍然需要如上所述检查是否存在/捕获异常(磁盘不在此类驱动器中)。