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 )))
相关推荐
新诺韦尔API1 天前
车架号查询接口对接全流程详解
大数据·开发语言·python·api
一人の梅雨1 天前
中国制造网关键字搜索接口实战:跨境B2B视角的精准匹配与本地化适配方案
人工智能·python·制造
hahahahanhanhan1 天前
Tensorflow使用GPU(cuda和cudnn和tensorflow下载)
人工智能·python·tensorflow·gpu
深度学习lover1 天前
<数据集>yolo毛毛虫识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·毛毛虫识别
坐在地上想成仙1 天前
从机床到键盘:用机械设计思维写出一个可部署网页
java·c++·python
Allen_LVyingbo1 天前
用Python实现辅助病案首页主诊断编码:从数据清洗到模型上线(上)
开发语言·python·github·知识图谱·健康医疗
傻啦嘿哟1 天前
Python家庭支出统计:从Excel到可视化图表的完整指南
开发语言·python·excel
子夜江寒1 天前
OpenCV部分操作介绍
图像处理·python·opencv·计算机视觉
轻竹办公PPT1 天前
2026 年 AI PPT 工具深度复盘:工具间的效率鸿沟与职场应用场景分析
人工智能·python·powerpoint
FJW0208141 天前
Python装饰器
开发语言·python