python 将多份word(.doc.docx)合成为一份,带选择文件夹界面

界面用于选择文件夹

小tips:文件夹内文件名必须是数字索引,文件夹内不能有除了数字意外的文件名

文件夹排序代码:

#按照.doc前的数字排序
docPath1.sort(key=lambda x: int(x.split('.')[0]),reverse=True)

总的代码代码如下:

写的比较粗糙,有更好的写法欢迎提出

import win32com.client as win32
import os
import tkinter as tk
from tkinter import filedialog
in_put=""

root = tk.Tk()
root.title("Folder selection")
root.geometry("460x300")
root.resizable(False,False)

#文件夹选择对话框
def select_in():
    global in_put
    in_put= filedialog.askdirectory()
    if in_put:
        file_label1.config(text=in_put)

#点击确定
def close_window():
    os.startfile(in_put)
    root.destroy()


#按钮绘制
button_in=tk.Button(root,text="Select the input folder",command=select_in)
button_in.place(x=20,y=20)

close_button = tk.Button(root, text="Confirm", command=close_window)
close_button.place(x=200,y=250)

#显示文件路径标签
file_label1=tk.Label(root,text="The folder name is displayed",font=("Arial",12),fg="blue")
file_label1.place(x=20,y=60)
root.mainloop()


word = win32.gencache.EnsureDispatch('Word.Application')
# 可视化运行
word.Visible = False
# 新建合并后空白文档
output = word.Documents.Add()

in_put=in_put.encode('utf-8').decode('unicode_escape')

# 需要合并的doc文件路径
docPath = in_put
# 输出文件路径,默认为doc目下的result.docx
outPath = docPath + '/' + 'result.doc'

# 需要合并的文档路径
files = []
docPath1=os.listdir(docPath)
print(docPath1)
docPath1.sort(key=lambda x: int(x.split('.')[0]),reverse=True)


for root, dirs, filnames in os.walk(docPath):
    filnames=docPath1
    for filename in filnames:
        if filename.endswith(('.docx', '.doc')):
            print(filename)
            files.append(root + '/' + filename)
    for file in files:
        output.Application.Selection.Range.InsertFile(file)

print(outPath)
output.SaveAs(outPath)
output.Close()


  • 8
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值