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(".") # 扫描当前目录