获取磁盘信息:已使用空间、总空间大小等,python没有自带的函数,常用的插件:WMI
python中自带的有获取文件夹大小、名称等信息的函数:walk()
环境:
win7、win8
python2.7.7
wmi:1.4.9
pywin32:pywin32-218.win-amd64-py2.7.exe
pywin32下载地址:https://sourceforge.net/projects/pywin32/files/pywin32/
注意:要下载和自己系统和所安装python版本相匹配的
因为依赖原因,在安装wmi之前需要先安装pywin32;
完成后拷贝解压后WMI-1.4.9文件夹到安装python的文件夹里面(C:/Python27/WMI-1.4.9)
然后在命令行执行:python */Python27/WMI-1.4.9/setup.py install
def get_disk_info():
"""
:return: get the disk info
"""
tmplist = []
c = wmi.WMI()
for physical_disk in c.Win32_DiskDrive():
tmpdict ={}
tmpdict["Caption"] = physical_disk.Caption
tmpdict["Size"] = int(physical_disk.Size)/1024/1024/1024
tmplist.append(tmpdict)
return tmplist
def get_fs_info():
"""
:return:get the file system info :contain partition's size ,used,avail ,operating frequency, mount info
"""
tmplist = []
c = wmi.WMI()
for physical_disk in c.Win32_DiskDrive():
for partition in physical_disk.associators("Win32_DiskDriveToDiskPartition"):
for logical_disk in partition.associators("Win32_LogicalDiskToPartition"):
tmpdict = {}
tmpdict["Caption"] = logical_disk.Caption
tmpdict["DiskTotal"] = int(logical_disk.Size)/1024/1024/1024
tmpdict["UseSpace"]=(int(logical_disk.Size)-int(logical_disk.FreeSpace))/1024/1024/1024
tmpdict["FreeSpace"]=int(logical_disk.FreeSpace)/1024/1024/1024
tmpdict["Percent"]=int(100.0*(int(logical_disk.Size)-int(logical_disk.FreeSpace))/int(logical_disk.Size))
tmplist.append(tmpdict)
return tmplist
def fssize(dirpath):
size = 0
if os.path.exists(dirpath):
if os.path.isdir(dirpath):
for root, dirs, files in os.walk(dirpath):
for name in files:
try:
size += getsize(join(root, name))
except:
continue
#size += sum([getsize(join(root, name)) for name in files])
elif os.path.isfile(dirpath):
size = os.path.getsize(dirpath)
else:
continue
return size
至于#size += sum([getsize(join(root, name)) for name in files])
在C盘会报错:error[5],没有权限。其他盘则正常工作。
本文出自he ivy 的博客,转载请注明出处:http://blog.csdn.net/heivy/article/details/51658223