使用python统计指定遍历文件夹深度下各文件夹大小

目录

1、背景

2、脚本实现

3、示例结果


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))

3、示例结果

  • 2
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值