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 )))
相关推荐
chase。2 分钟前
Python包构建工具完全指南:python -m build 使用详解
开发语言·chrome·python
xin_yao_xin6 分钟前
PaddleOCR系列——《文本检测、文本识别》模型训练
人工智能·python·paddlepaddle·ppocr
2401_833197737 分钟前
用Python制作一个文字冒险游戏
jvm·数据库·python
万粉变现经纪人24 分钟前
如何解决 pip install cx_Oracle 报错 未找到 Oracle Instant Client 问题
数据库·python·mysql·oracle·pycharm·bug·pip
sw12138925 分钟前
使用Plotly创建交互式图表
jvm·数据库·python
2301_8101609527 分钟前
如何为开源Python项目做贡献?
jvm·数据库·python
若惜28 分钟前
selenium自动化测试web自动化测试 框架封装Pom
前端·python·selenium
weixin_4577600034 分钟前
基于pytorch实现LPR模型车牌识别
人工智能·pytorch·python·深度学习·lpr
Zaly.36 分钟前
【Python刷题】LeetCode 3567 子矩阵的最小绝对差
python·leetcode·矩阵
2501_9454235442 分钟前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python