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 )))
相关推荐
三万棵雪松2 小时前
【AI小智后端部分(一)】
人工智能·python·ai小智
laplace01232 小时前
Part 3:模型调用、记忆管理与工具调用流程(LangChain 1.0)笔记(Markdown)
开发语言·人工智能·笔记·python·langchain·prompt
winfredzhang2 小时前
深度解析:利用 Python + Playwright 攻克动态网页 PPT 导出难题
python·powerpoint·截图·自动翻页
风送雨2 小时前
八周Python强化计划(七)
开发语言·python
ππ很开心6663 小时前
DAY 32 函数专题2:装饰器
开发语言·python
山沐与山3 小时前
LangChain Tools解析:让Agent拥有超能力
人工智能·python·langchain
TonyLee0173 小时前
python代码运行时间信息记录
python
曲幽3 小时前
手把手搞定FastAPI静态文件:安全、上传与访问
css·python·fastapi·web·js·favicon·staticfiles
sandwu3 小时前
AI Agent——可观测性链路集成&评测体系搭建(Langfuse)
人工智能·python·langchain·langfuse