import os
from docx import Document
from docx.enum.text import WD_BREAK
def replace_text_in_headers(folder_path, old_text, new_text):
# 遍历文件夹中的所有文件
for filename in os.listdir(folder_path):
if filename.endswith('.docx'):
# 构建完整的文件路径
file_path = os.path.join(folder_path, filename)
doc = Document(file_path)
# 遍历文档中的所有节
for section in doc.sections:
# 获取页眉
header = section.header
# 如果有页眉内容,则替换文本
if header:
for paragraph in header.paragraphs:
for run in paragraph.runs:
# 检查并替换文本
text = run.text.replace(old_text, new_text)
run.text = text
# 保存修改后的文档