先安装python环境
接着安装依赖 ,采用docxcompose 依赖包 进行合并word,执行如下命令进行安装
pip install docxcompose
from docxcompose.composer import Composer
from docx import Document
import os
def merge_with_docxcompose(doc_list, output_path):
master = Document(doc_list[0])
composer = Composer(master)
for doc_path in doc_list[1:]:
doc = Document(doc_path)
composer.append(doc)
composer.save(output_path)
# 定义包含所有需要合并的Word文档路径的列表
documents_to_merge = []
document_dir = './file3'
# 检查目录是否存在
if not os.path.exists(document_dir):
raise FileNotFoundError(f"目录 {document_dir} 不存在")
# 获取所有.docx文件
for file in sorted(os.listdir(document_dir)):
if file.endswith('.docx'):
full_path = os.path.join(document_dir, file)
documents_to_merge.append(full_path)
if not documents_to_merge:
raise ValueError("没有找到任何.docx文件进行合并")
output_file = 'merged_document5.docx'
# merge_documents(documents_to_merge, output_file)
merge_with_docxcompose(documents_to_merge, output_file)
print(f"文档已成功合并到 {output_file}")
代码说明: document_dir 是 要合并的文件目录 ;output_file 是合成后的文件 。
依赖包对比: 使用 python-docx 进行合并时, 图片无法合并到新文档中, 使用docxcompose 图片可合并到新文档中。
如果还无法解决实际需求 可考虑
先将每个文档转为 PDF(使用
python-docx2pdf
)合并 PDF(使用
PyPDF2
)再将合并后的 PDF 转回 Word(如果需要)