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 )))
相关推荐
Generalzy13 分钟前
Qt 桌面开发入门:PySide6 学习路线、架构原理与技术选型
笔记·python·学习
Mr.D学长14 分钟前
毕业设计项目 基于机器视觉的车牌识别系统
python·毕业设计·毕设
云和数据.ChenGuang30 分钟前
AI 工程师相关就业岗位(细分,偏工程落地,由底层到上层)
服务器·开发语言·人工智能·python
Web3&Basketball40 分钟前
litellm 做 Agent 成本监控:3 个账单维度实战
python·大模型·agent·可观测性·litellm·成本控制·llm运维
Mr.D学长1 小时前
毕业设计项目 基于python的答题卡识别评分系统
python·毕业设计·毕设
云和数据.ChenGuang1 小时前
LangChain 实战指南:从入门到构建智能应用
开发语言·人工智能·python·langchain
青少儿编程课堂1 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会C/C++考级:拓扑排序课程表排课解析
c++·python·算法·bfs·信息学竞赛
const_qiu1 小时前
第三章 04:3.6 基础调用链的构建
开发语言·python
向上的车轮1 小时前
Python 大数据处理不慢:Polars + DuckDB + Arrow 实战指南
开发语言·python
程序员小孔.1 小时前
基于 SpringBoot + UniApp + Vue 的家政服务系统设计与实现
前端·数据库·spring boot·python·docker·微信小程序