Python脚本查询目标文件夹以及子文件夹的大小

源码:

import os

def calculate_folder_size(folder_path):
    total_size = 0
    folder_sizes = {}  # Dictionary to store folder sizes

    for root, dirs, files in os.walk(folder_path):
        folder_total = 0  # Initialize size for the current folder

        for file in files:
            file_path = os.path.join(root, file)
            file_size = os.path.getsize(file_path)
            total_size += file_size
            folder_total += file_size  # Accumulate size for the current folder

        # Save the size of the current folder
        folder_sizes[root] = folder_total

    return total_size, folder_sizes

# Example usage
folder_path = r'C:\Users\Administrator\Desktop\r'
total_size, folder_sizes = calculate_folder_size(folder_path)

print(f'Total Folder Size: {total_size} bytes')
print(f'Total Folder Size: {total_size / 1024:.2f} KB')
print(f'Total Folder Size: {total_size / 1024 / 1024:.2f} MB')
print(f'Total Folder Size: {total_size / 1024 / 1024 / 1024:.2f} GB')

print("\nSizes of each subfolder:")
for folder, size in folder_sizes.items():
    print(f"{folder}: {size} bytes ({size / 1024:.2f} KB, {size / 1024 / 1024:.2f} MB, {size / 1024 / 1024 / 1024:.2f} GB)")

ps:

folder_path为目标文件夹

文件夹大小计算:代码现在分别计算每个子文件夹的大小并将其存储在字典 (folder_sizes) 中。

输出格式:总大小和各个文件夹的大小以更易读的格式打印,包括转换为千字节 (KB) 和兆字节 (MB)。

动态输出:程序动态报告所有子文件夹的大小,让您轻松了解每个子文件夹占用的空间。

工作原理:
os.walk():此函数遍历目录树,生成目录路径、子目录和每个目录中的文件。
文件夹大小计算:脚本将每个文件夹中所有文件的大小相加,并将其记录在 folder_sizes 字典中。

打印台:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值