我想获取所有本地磁盘及其分区,然后返回所有数据,如“总空间,已用空间和可用空间”。问题是检查分区是否存在然后如果没有错误则继续结束。
在下面的代码中,我的本地磁盘有三个分区: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?)。
这可能仍然需要检查存在/捕获异常(磁盘不在驱动器中),如上所述。