Python递归获取目录大小

为了方便统计目录大小,写了2个函数,一个用来统计目录大小,单位是字节;连一个将大小,转成可视化的单位,比如2.1GB。

python 复制代码
import os


def get_dir_size(dir_path):
    """
    统计目录大小
    :param dir_path: 目录名
    :return: int 目录大小
    """
    if not os.path.isdir(dir_path):
        print('%s 不是个目录!' % dir_path)
        return
    files = os.listdir(dir_path)
    # print(files)
    total_size = 0
    for file in files:
        # print(image)
        file_path = os.path.join(dir_path, file)
        total_size += os.path.getsize(file_path)
    # print(total_size)
    
    return total_size 


def change_size_to_text(total_size):
    """
    将字节转为可视化的文本
    :param total_size: int
    :return: text
    """
    gb_size = 1.0 * 1024 * 1024 * 1024
    mb_size = 1.0 * 1024 * 1024
    kb_size = 1.0 * 1024
    if total_size <= kb_size:
        total_size_format = '%.2f B' % round(total_size, 2)
    elif total_size <= mb_size:
        total_size_format = '%.2f KB' % round(total_size / kb_size, 2)
    elif total_size <= gb_size:
        total_size_format = '%.2f MB' % round(total_size / mb_size, 2)
    elif total_size > gb_size:
        total_size_format = '%.2f GB' % round(total_size / gb_size, 2)
    return total_size_format


if __name__ == '__main__':
    dirpath = './test-dir/'
    print(get_dir_size(dirpath ))
    print(change_size_to_text(get_dir_size(dirpath )))
相关推荐
powerfulhell3 分钟前
寒假python作业5
java·前端·python
铉铉这波能秀10 分钟前
LeetCode Hot100 中 enumerate 函数的妙用(2026.2月版)
数据结构·python·算法·leetcode·职场和发展·开发
毕设源码-赖学姐12 分钟前
【开题答辩全过程】以 基于python的电影推荐系统为例,包含答辩的问题和答案
开发语言·python
敲键盘的生活14 分钟前
MoneyPrinter重构之一:用nicegui调用大模型生成视频文案
python·重构·aigc·ai编程·ai写作
小邓睡不饱耶16 分钟前
2026 CSDN榜单封神!3大热门技术+5个大厂案例,新手也能直接抄作业
python·ai
南极星100520 分钟前
我的创作纪念日--128天
java·python·opencv·职场和发展
码界筑梦坊21 分钟前
327-基于Django的兰州空气质量大数据可视化分析系统
python·信息可视化·数据分析·django·毕业设计·数据可视化
Highcharts.js21 分钟前
如何使用Highcharts SVG渲染器?
开发语言·javascript·python·svg·highcharts·渲染器
啊阿狸不会拉杆27 分钟前
《机器学习导论》第 7 章-聚类
数据结构·人工智能·python·算法·机器学习·数据挖掘·聚类
摇滚侠27 分钟前
Java,举例说明,函数式接口,函数式接口实现类,通过匿名内部类实现函数式接口,通过 Lambda 表达式实现函数式接口,演变的过程
java·开发语言·python