目录
1、背景
电脑有时磁盘会被莫名软件占用较大空间,人为一个个文件查找确认大小较麻烦,此脚本可实现在给定文件夹路径,给定查找的深度下,统计该深度下各文件夹大小,以及深度下非文件夹的文件总大小
2、脚本实现
import os
class file_size:
"""compiled on 20220827"""
def __init__(self):
pass
#计算文件夹file_path的大小
def cal_size(self,file_path):
sum=0
try:
os.listdir(file_path)
except:
pass
else:
for f in os.listdir(file_path):
abspath=os.path.join(file_path,f)
if os.path.isfile(abspath):
sum+=os.path.getsize(abspath)
elif os.path.isdir(abspath):
sum+=self.cal_size(abspath)
return sum
#转换成可读的数据kb,MB,GB
def convert(self,size):
if size<1024:
return str(size)+" bytes"
elif 1024 <=size<1024*1024:
return str(round(size/1024,2))+" kb"
elif 1024*1024<=size<1024*1024*1024:
return str(round(size/(1024*1024),2))+" MB"
else:
return str(round(size/(1024*1024*1024),2))+" GB"
#根据指定文件夹的遍历深度depth,计算该深度下各文件夹的大小
def GetDirSize(self,file_path,depth):
depth=int(depth)-1
direc=os.listdir(file_path)
file_size=0
for f in direc:
path=os.path.join(file_path,f)
if os.path.isfile(path):
file_size+=os.path.getsize(path)
f_read=self.convert(file_size)
# print("文件{}的大小是{}:".format(path,f_read))
elif int(depth)<=0:
dir_size=self.cal_size(path)
d_read=self.convert(dir_size)
print("文件夹{}的大小是:{}".format(path,d_read))
continue
else:
self.GetDirSize(path,str(depth))
print("文件总大小是:",self.convert(file_size))
if __name__=="__main__":
file_path=r"C:\\" #查找路径为C盘
depth=1 #查找C盘深度为1,即C盘中直属文件夹的大小
file_size=file_size()
print(file_size.GetDirSize(file_path,depth))