环境准备:
系统 | Windows |
语言 | Python3.8 |
开发工具 | Pycharm |
import os
import comtypes.client
def delete_first_page(doc_path):
# 获取Word应用程序对象
word = comtypes.client.CreateObject('Word.Application')
word.Visible = 0 # 不可见
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"):#word文档格式后缀
file_path = os.path.join(root, file)
delete_first_page(file_path)
print(f"Processed {file_path}")
# 使用函数处理目录下的所有Word文件
process_directory(r"E:\yourword\")
标签:word,批量,删除,doc,Word,file,directory,path
From: https://blog.csdn.net/m0_61570062/article/details/143506745