AlexRomeo
发布于 2024-07-04 / 76 阅读
1
0

批量删除word文件第一页

批量删除word文件第一页

环境:

windows11

Python 3.8.8

代码如下

import os
import comtypes.client

def delete_first_page(doc_path):
    # 获取Word应用程序对象
    word = comtypes.client.CreateObject('Word.Application')
    word.Visible = 0 # 不可见

    # 打开Word文档
    doc = word.Documents.Open(doc_path)

    try:
        # 将光标移动到文档的第一页
        word.Selection.GoTo(What=1, Which=1)

        # 选择第一页的内容并删除
        word.Selection.Bookmarks("\Page").Range.Delete()

        # 保存更改后的文档
        doc.Save()
    except Exception as e:
        print(f"Failed to delete the first page of {doc_path}: {e}")
    finally:
        # 关闭文档和Word应用程序
        doc.Close()
        word.Quit()

def process_directory(directory_path):
    for root, dirs, files in os.walk(directory_path):
        for file in files:
            if file.endswith(".docx") or file.endswith(".doc"):
                file_path = os.path.join(root, file)
                delete_first_page(file_path)
                print(f"Processed {file_path}")

# 使用函数处理目录下的所有Word文件
process_directory(r"D:\TestDir\")

评论