需求
最近有一个项目方案,涉及到2000多个文档。之前公司有相关案例,但是需要将2000多个文档中的特殊名称改成现有项目,单独操作需要打开每个文档区搜索替换,费事费力。通过python中对文档的操作进行批量替换。
方案思路
1.获取所有需要替换的word文件路径
def getdocreplace(path):
files=[]
for dirpath, dirnames, filenames in os.walk(path):
for filepath in filenames:
if filepath.endswith(".doc") or filepath.endswith("docx"):
files.append(os.path.join(dirpath, filepath))
return files
2.批量打开word,遍历循环word中的每一行进行查找替换,核心代码如下
def info_update(docfile,old_info,new_info):
for para in docfile.paragraphs:
for run in para.runs:
run.text = run.text.replace(old_info,new_info)
for table in docfile.tables:
for row in table.rows:
for cell in row.cells:
cell.text = cell.text.replace(old_info,new_info)
心得体会
python真是一个好用的编程语言,语法简单,代码简洁易于编写。同时python社区有各种各样的python库,具有强大的功能。如这次简单的一个案例,如果人工去改上千的文档,需要大量时间。通过python简单的几十行代码,很短的时间就能完成大量工作。而且学习容易,入门简单。
之前还有很多解决日常工作中的案例以及以后还会用的更多的案例我会分享到51。下面是本次案例的全部代码。本段功能需要引用os和docx两个库。我使用的python版本为3.7。
import os
import docx
#获取要替换的所有文件路径,path为最外层文件夹。
def getdocreplace(path):
files = []
for dirpath,dirnames,filenames in os.walk(path):
for filepath in filenames:
if filepath.endswith(".doc") or filepath.endswith("docx"):
files.append(os.path.join(dirpath,filepath)
return files
#遍历替换一个word文件中的字段,old_info为要替换的旧字段,new_info为新字段
def info_update(docfile,old_info,new_info):
for para in docfile.paragraphs:
for run in para.runs:
run.text = run.text.replace(old_info,new_info)
for table in docfile.tables:
for row in table.rows:
for cell in row.cells:
cell.text = cell.text.replace(old_info,new_info)
#执行操作
if __name__ =="__main__":
path = "d:\docfile"
files = getdocreplace(path)
for file in files:
doc = docx.Document(file)
info_update(doc,"old_project","new_project")
doc.save(file)
print("{}替换完成".format(file))
标签:info,word,filepath,Python,text,old,文档,new,path
From: https://blog.51cto.com/u_16221091/7026420