将指定文件夹下word内容合并到一个word文档
from docx import Document
from docx.shared import Inches
import os
import re
import win32com.client as win32
import pandas as pd
def combine_docx(path,path_last,path_save):
os.chdir(path)
#读取指定文件夹内的文件名字
file_name = []
for root, dirs, files in os.walk(path_last):
for file in files:
file_name.append(os.path.join(root, file))
#将多个word文档合并并保存在指定路径
word = win32.gencache.EnsureDispatch('Word.Application')# 打开word软件
word.Visible = False# 非可视化运行
output = word.Documents.Add() # 新建合并后空白文档
files =file_name # 需要合并的文档路径
files_error=[]
for file in files:
try:
file_path_=os.path.join(path,file)
output.Application.Selection.Range.InsertFile(file_path_) # 拼接文档
except:
files_error.append(file)
continue
doc = output.Range(output.Content.Start, output.Content.End)# 获取合并后文档的内容
output.SaveAs(path_save) # 保存
output.Close()
return files_error
if __name__=='__main__':
path='E:\课件\研一下\金融工程'#至倒数第三层文件路径
path_last='月考'#文件倒数第二层路径
path_save='E:\课件\研一下\金融工程\合并文档_月考.docx'#目标保存路径
combine_docx(path, path_last, path_save)