【Python】批量删除word文件中的页眉页脚

背景:想对一个文件下下的文件及子目录的word文件批量删除页眉页脚,过程中出现document不能打开doc的文件,需要先将doc文件转换为docx文件。通过Win32com解决doc转换docx后,测试一直在单个目录下,未出现其他问题。当切换到实际目录时出现:pywintypes.com_error: (-2147352567, ‘发生意外。‘, (0, ‘Kingsoft WPS‘, ‘文档保存失败。‘, ‘‘, 3011, -214746725)) 的问题。
查找资料,以为是wps的问题,或者文件频繁打开保存导致。还一度引入time库去看文件处理的时间,没有怀疑是自己的文件路径问题。最后通过https://blog.csdn.net/q7w8e9r4/article/details/133701132,还是去print了自己的文件路径,最终解决了该问题。
以下代码仅供参考,大神轻喷
【code】:
import os
import time
import shutil
import win32com.client
from docx import Document

# 删除word文档中的页眉页脚
def delete_docx_header_footer(file_path):
    # print(file_path)
    doc = Document(file_path)
    for section in doc.sections:
        i = 0
        header = section.header
        footer = section.footer
        if header is not None and len(header.paragraphs) > 0:
            while len(header.paragraphs) > 0:
                paragraph = header.paragraphs[0]
                header._element.remove(paragraph._element)
        if footer is not None and len(footer.paragraphs) > 0:
            while len(footer.paragraphs) > 0:
                paragraph = footer.paragraphs[0]
                footer._element.remove(paragraph._element)
    doc.save(file_path)

#将doc文件转换为docx文件
def doc_to_docx(root_path, file_name):
    old_path: str = root_path + '\\' + file_name + '.doc'
    new_path: str = root_path + '\\' + file_name + '.docx'
    word = win32com.client.Dispatch("Word.Application")
    word.Visible = 0
    word.DisplayAlerts = 0
    doc = word.Documents.Open(old_path)  # 注意Documents后边有s
    doc.SaveAs(new_path, 12)# 注意首字母大写
    doc.Close()# 注意首字母大写
    word.Quit()# 注意首字母大写
    os.remove(old_path)
    print('\n')

    return new_path

#程序入口
folder_path = 'C:\\Users\\xiaol\\Desktop\\'
file_list = []

#循环获取word并保存到文件数组中
for root, dirs, files in os.walk(folder_path):
    for file in files:
        end: str = file.split('.')[-1]
        file_name: str = file.split('.')[0]
        if end == 'docx':
            file_list.append(os.path.join(root, file))#加入文件数组
        if end == 'doc':
            new_path: str = doc_to_docx(root, file_name)#把转换后的docx文件加入到文件数组
            file_list.append(new_path)
for file_path in file_list:
    delete_docx_header_footer(file_path)#删除页眉页脚
  • 23
    点赞
  • 23
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值