import os
from docx import Document
import Pillow
from docx.shared import Inches
# 定义你想要遍历的文件夹路径
folder_path = 'C:/Users/Administrator/Desktop/新建文件夹 (2)'
# 遍历文件夹中的所有子文件夹
for subdir, dirs, files in os.walk(folder_path):
first_level_dir_name = os.path.basename(os.path.dirname(subdir))
last_level_dir_name = os.path.basename(subdir)
# 在每个子文件夹中创建一个新的docx文档
if last_level_dir_name == '2023-09-05':
doc = Document()
# 创建文档
print(first_level_dir_name)
# 在文档中添加一个三列若干行的表格
table = doc.add_table(rows=len(files), cols=3)
# 获取当前目录下的所有.png文件的路径
png_files = [os.path.join(subdir, f) for f in files if f.endswith('.png')]
# 将图片按照顺序插入到表格中
for i, png_file in enumerate(png_files):
# 计算图片应该插入的单元格位置
row = i // 3
col = i % 3
# 在特定的单元格中添加图片
cell = table.cell(row, col)
paragraph = cell.add_paragraph()
run = paragraph.add_run()
run.add_picture(png_file, width=Inches(1.25), height=Inches(1.25))
# 保存文档
doc.save(os.path.join(subdir, first_level_dir_name + '.docx'))
else:
doc = Document()
print(last_level_dir_name)
# 创建文档
# 在文档中添加一个三列若干行的表格
table = doc.add_table(rows=len(files), cols=3)
# 获取当前目录下的所有.png文件的路径
png_files = [os.path.join(subdir, f) for f in files if f.endswith('.png')]
# 将图片按照顺序插入到表格中
for i, png_file in enumerate(png_files):
# 计算图片应该插入的单元格位置
row = i // 3
col = i % 3
# 在特定的单元格中添加图片
cell = table.cell(row, col)
paragraph = cell.add_paragraph()
run = paragraph.add_run()
run.add_picture(png_file, width=Inches(1.25), height=Inches(1.25))
# 保存文档到子文件夹中,使用当前子文件夹的名称作为文档名称
doc.save(os.path.join(subdir, last_level_dir_name + '.docx'))