欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python批量修改word文档内容

程序员文章站 2022-04-18 18:47:44
...

实现的目标

批量word文档内容

用到的python模块

pip install python-docx

脚本内容

#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
import docx
import sys

#需替换文档目录
path = u'G:\文档修改'
#自动创建
tlog =  path + u'\替换文档列表.txt'
err_log = path + u'\替换出错列表.txt'

try:
    os.makedirs(save_path)
except:
    pass

if sys.getdefaultencoding() != 'utf-8':
    reload(sys)
    sys.setdefaultencoding('utf-8')

def log(text):
    with open( err_log,"a+" ) as f:
        f.write(text)
        f.write('\n')
def log2(text):
    with open( tlog,"a+" ) as f:
        f.write(text)
        f.write('\n')



def info_update(doc,old_info,new_info):
    for para in doc.paragraphs:
        for run in para.runs:
            run.text = run.text.replace(old_info,new_info)

    for table in doc.tables:
        for row in table.rows:
            for cell in row.cells:
                cell.text = cell.text.replace(old_info,new_info)


                
def thr(old_info,new_info):
    for parent, dirnames, filenames in os.walk(path):
        for fn in filenames:
            filedir = os.path.join(parent, fn)
            if fn.endswith('.docx'):
                try:
                    doc = docx.Document(filedir)
                    info_update(doc,old_info,new_info)
                    doc.save(filedir)
                    log2(filedir + ' 修改完成')
                    print(filedir + ' 修改完成')
                except Exception as e:
                    log(filedir)


if __name__ == '__main__':
    thr('大哥','小弟')
    print('----全部替换完成----')