#conding = utf-8
import os
from docx import Document
#旧docx文件目录
old_file_path = 'E:\pro\docx'
#生成新文件目录
new_file_path = 'E:\pro\docx'
replace_dict ={
'第一范文网':'汇文网',
'第一范文':'汇文网',
} #替换字典
def check_and_change(document,replace_dict):
for para in document.paragraphs:
for i in range(len(para.runs)):
for key,value in replace_dict.items():
if key in para.runs[i].text:
print(key+"-->"+value)
para.runs[i].text = para.runs[i].text.replace(key,value)
return document
def main():
for name in os.listdir(old_file_path):
print(name)
old_file = old_file_path + name
new_file = new_file_path + name
if old_file.split('.')[-1] == 'docx': #触发替换函数
document = Document(old_file)
document = check_and_change(document,replace_dict)
document.save(new_file)
print('^'*30)
if __name__ == '__main__':
main()