下面是一个示例代码,可以按照年月汇总文件大小,并打印年度总计:
import os
from collections import defaultdict
# 获取指定目录下的所有文件
def get_files(directory):
files = []
for dirpath, _, filenames in os.walk(directory):
for filename in filenames:
files.append(os.path.join(dirpath, filename))
return files
# 按年月汇总文件大小
def summarize_file_size(files):
file_size_by_month = defaultdict(int)
for file in files:
file_size = os.path.getsize(file)
file_year = str(os.path.getmtime(file)).split(".")[0][:4]
file_month = str(os.path.getmtime(file)).split(".")[0][4:6]
file_size_by_month[(file_year, file_month)] += file_size
return file_size_by_month
# 打印汇总结果,包括年度总计
def print_summary(file_size_by_month):
total_by_year = defaultdict(int)
for (file_year, file_month), size in file_size_by_month.items():
print(f"{file_year}-{file_month}: {size} bytes")
total_by_year[file_year] += size
print("Yearly total:")
for year, total in total_by_year.items():
print(f"{year}: {total} bytes")
# 测试
directory = "path/to/directory" # 指定要统计的目录
files = get_files(directory)
file_size_by_month = summarize_file_size(files)
print_summary(file_size_by_month)
请替换path/to/directory
为你要统计的目录的实际路径。运行代码后,将会打印出按年月汇总的文件大小,并在最后打印出年度总计。