对目录下不同文件类型的数量进行统计,并写入到xlsx文件中。
import os
from openpyxl import Workbook
from collections import defaultdict
def dir_file_class_num(
file_dir_path, xlsx_path,
sheet_name="不同文件类型数量统计"
):
wb_write = Workbook()
del wb_write[wb_write.sheetnames[0]]
ws = wb_write.create_sheet(sheet_name)
file_count_dict = defaultdict(int)
# 遍历目录及其子目录
for root, dirs, files in os.walk(file_dir_path):
for file in files:
# 分离文件名和扩展名
filename, file_extension = os.path.splitext(file)
if file_extension:
# 统计不同扩展名的文件数量
file_count_dict[file_extension] += 1
title_row_name_list = ["文件类型", "数量", "总数"]
for i, name in enumerate(title_row_name_list):
ws.cell(row=1, column=i + 1, value=name)
for i, (file_extension, count) in enumerate(file_count_dict.items()):
ws.cell(row=i + 2, column=1, value=file_extension)
ws.cell(row=i + 2, column=2, value=count)
ws.cell(row=2, column=3, value=sum(file_count_dict.values()))
wb_write.save(xlsx_path)
if __name__ == "__main__":
dir_path = "./test_dir"
xlsx_path = "./不同文件类型数量统计.xlsx"
dir_file_class_num(
dir_path ,
xlsx_path,
sheet_name="不同文件类型数量统计"
)