python-archieve-projects/移除Word页眉.py

48 lines
1.8 KiB
Python
Executable File
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import os
from docx import Document
# 要批量修改的Word文档所在目录
dir_path = 'X:\\UserDoc\\Download\\Baidu\\2021'
def collect_subdirectories(directory):
subdirectories = []
for root, dirs, files in os.walk(directory):
for dir in dirs:
subdirectories.append(os.path.join(root, dir))
return subdirectories
# 收集所有子目录的路径
subdirectories = collect_subdirectories(dir_path)
if len(subdirectories) == 0:
subdirectories = [dir_path]
# 遍历目录下的所有Word文档
for subdirectory in subdirectories:
print(subdirectory)
for filename in os.listdir(subdirectory):
print(filename)
if filename.endswith('.docx'):
# 打开文档
doc = Document(os.path.join(subdirectory, filename))
# 获取页眉
header = doc.sections[0].header
# 修改页眉中的文本
header_text = header.paragraphs[0].text if header.paragraphs else ""
new_header_text = "更多资源请添加微信wanzi3345"
if header_text == "":
header.paragraphs[0].text = new_header_text
else:
for paragraph in header.paragraphs:
if len(paragraph.runs) == 1:
paragraph.runs[0].text = "更多资源请添加微信wanzi3345"
elif len(paragraph.runs) == 2:
paragraph.runs[0].text = "更多资源请添加微信wanzi3345"
paragraph.runs[1].text=""
# paragraph.runs[0].text = 'aaaa'
# for run in paragraph.runs:
# run.text = '添加我'
# 保存文档
doc.save(os.path.join(subdirectory, filename))