python-查看当前文件下每个子文件夹的占用大小以及文件个数

import os
from pathlib import Path

def get_folder_size(path):
    total_size = 0
    file_count = 0
    for dirpath, dirnames, filenames in os.walk(str(path)):  # 转换为字符串
        for f in filenames:
            fp = os.path.join(dirpath, f)
            total_size += os.path.getsize(fp)
            file_count += 1
    return total_size, file_count

def print_folder_stats(root_dir):
    root_path = Path(root_dir)
    print("Scanning directory: %s\n" % root_path)
    
    # Print header
    print("%-50s %15s %10s" % ('Folder', 'Size (MB)', 'Files'))
    print("-" * 80)
    
    # Get stats for all subdirectories
    for item in os.scandir(str(root_path)):  # 转换为字符串
        if item.is_dir():
            size_bytes, file_count = get_folder_size(item.path)
            size_mb = size_bytes / (1024 * 1024)
            print("%-50s %15.2f %10d" % (item.name, size_mb, file_count))
    
    # Print total
    total_size_bytes, total_files = get_folder_size(root_path)
    total_size_mb = total_size_bytes / (1024 * 1024)
    print("-" * 80)
    print("%-50s %15.2f %10d" % ('TOTAL', total_size_mb, total_files))

# 使用方法
print_folder_stats(".")  # 扫描当前目录

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值