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 )))
相关推荐
Dxy123931021619 分钟前
Python路径算法简介
开发语言·python·算法
躺平的赶海人28 分钟前
python opencv实现相机内参标定之安装OpenCv
python·opencv·计算机视觉
满满和米兜28 分钟前
【Java基础】-I/O-字符流
java·开发语言·python
echome88840 分钟前
Python 装饰器详解:从入门到精通的 7 个实用案例
开发语言·python
子木HAPPY阳VIP41 分钟前
【无标题】
java·python·mysql
2501_921649491 小时前
低延迟量化交易数据 API:从架构设计到性能优化的完整实践指南
python·websocket·金融·量化
无心水1 小时前
2、5分钟上手|PyPDF2 快速提取PDF文本
java·linux·分布式·后端·python·架构·pdf
代码的乐趣1 小时前
支持selenium的chrome driver更新到147.0.7727.56
chrome·python·selenium
码上实战1 小时前
到底Java 适不适合做 AI 呢?
java·人工智能·后端·python·ai
reasonsummer1 小时前
【教学类-160-02】20260409 AI视频培训-练习2“豆包AI视频《小班-抢玩具》+豆包图片风格:手办”
python·音视频·ai视频·豆包·通义万相