跳到主要内容

删除DOCX页眉页脚

文章信息

创建日期:2025年1月13日

从网上下载的很多教学资料有页眉和页脚,这个脚本可以快速删除所有文件的页眉和页脚。

代码如下:

import os
from docx import Document

def remove_headers_footers(doc_path):
try:
# 打开文档
doc = Document(doc_path)

# 删除页眉
for section in doc.sections:
section.header.is_linked_to_previous = False
for paragraph in section.header.paragraphs:
paragraph.text = ""

# 删除页脚
for section in doc.sections:
section.footer.is_linked_to_previous = False
for paragraph in section.footer.paragraphs:
paragraph.text = ""

# 保存修改后的文档
doc.save(doc_path)
print(f"处理完成: {doc_path}")
except Exception as e:
print(f"处理 {doc_path} 时出错: {e}")

def process_docx_in_directory(directory):
# 遍历指定目录下的所有文件
for root, _, files in os.walk(directory):
for file in files:
if file.endswith(".docx"):
file_path = os.path.join(root, file)
remove_headers_footers(file_path)

if __name__ == "__main__":
# 输入目录路径
target_directory = input("请输入包含DOCX文件的目录路径: ").strip()
if os.path.isdir(target_directory):
process_docx_in_directory(target_directory)
else:
print("目录路径无效,请检查后重新运行脚本。")