工作需要需要把一批word文档的页眉修改成统一名称,在网上看到一些文章,自己写了代码,记录免得未来忘了。
首先安装python-docx,命令行运行:
pip install python-docx -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
然后写一个枚举文件夹文件函数:
def findfilewith(folder,includestr=None):
resultfileList=[]
with os.scandir(folder) as it:
for entry in it:
if not entry.name.startswith(‘.’) and entry.is_dir():
filelist=findfilewith(entry.path,includestr)
if len(filelist)>0:
resultfileList.extend(filelist)
elif entry.is_file:
if includestr is None:
resultfileList.append(entry.path)
elif includestr in entry.name:
resultfileList.append(entry.path)
return resultfileList
第三写一个改一个文件页眉的函数
def replaceHeader(sReplaceText,sFileName):
if sFileName.endswith(“.docx”) and (“~$” not in sFileName):
#形成docx对象
document=Document(sFileName)
#页眉
header = document.sections[0].header
#页眉第一段
paragraph = header.paragraphs[0]
#设置页眉,即使原来有页眉也可以替换
paragraph.text=sReplaceText
#保存
document.save(sFileName)
else:
print(“Not doc File”)
整体函数:
import os
from os import path
from docx import Document
#sFolder预先定义想搜索的文件夹
docFileList=findfilewith(sFolder)
#replaceText想替换的内容,自定义
for file in docFileList:
replaceHeader(replaceText,file)
print(“ok”)
经过测试把文件夹word的页眉都修改成功了
参考的文档:python-docx设置页眉和页脚