源码:
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 字典中。