python win系統獲取磁碟及資料夾大小
阿新 • • 發佈:2019-01-31
獲取磁碟資訊:已使用空間、總空間大小等,python沒有自帶的函式,常用的外掛:WMI
python中自帶的有獲取資料夾大小、名稱等資訊的函式:walk()
使用wmi之前的配置
環境:
win7、win8
python2.7.7
wmi:1.4.9
pywin32:pywin32-218.win-amd64-py2.7.exe
注意:要下載和自己系統和所安裝python版本相匹配的
因為依賴原因,在安裝wmi之前需要先安裝pywin32;
完成後拷貝解壓後WMI-1.4.9資料夾到安裝python的資料夾裡面(C:/Python27/WMI-1.4.9)
然後在命令列執行:python */Python27/WMI-1.4.9/setup.py install
例項
getdiskinfo
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
getfsinfo
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],沒有許可權。其他盤則正常工作。