202104修改文件名

import os
from docx import Document

# 放了一些docx 文件
old_file_path = "D:/test"
# 生成新文件后的存放地址
new_file_path = "D:/test/a"
replace_dict = {
    "TS-PM-434诃子肉饮片工艺规程(A00版)": "TS-PM-K434诃子肉饮片工艺规程(A00版)",

}

def check_and_change(document, replace_dict):
    """
    遍历word中的所有 paragraphs,在每一段中发现含有key 的内容,就替换为 value 。 
    (key 和 value 都是replace_dict中的键值对。)
    """
    for para in document.name:
        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()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值