py 替换文件内容例子(按照字典替换)

#!/usr/bin/env python

import os
import re
import json

def get_all_file(dir_path,target_file):
    '''
    获取dir_path下所有扩展名在target_file内的文件完整路径
    :param dir_path: str,目标文件夹
    :param target_file: list,目标扩展名列表
    :return:
    '''
    all_file_path = []
    for file in os.listdir(dir_path):
        # 如果是文件夹递归调用get_all_file
        if os.path.isdir(dir_path + '/' + file):
            temp_file_path = get_all_file(dir_path + '/' + file,target_file)
            all_file_path = all_file_path + temp_file_path
        # 如果是文件判断其扩展名
        elif os.path.isfile(os.path.join(dir_path, file)):
            file_path = dir_path + '/' + file
            if file.split('.')[-1] in target_file:
                all_file_path.append(file_path)
    return all_file_path

if __name__=='__main__':
    input_path='./emage-common'
    output_path = './output'
    target_file = ['html','java','js']
    with open('./replace_dict.json', 'r', encoding='utf-8') as f:
        replace_dict=json.load(f)
    if os.path.exists(output_path):
        pass
    else:
        os.mkdir(output_path)
    # 递归获取input_path下所有扩展名为java的文件
    all_file_paths = get_all_file(input_path,target_file)
    count = {}
    for file_path in all_file_paths:
        count[file_path] = {}
        # 获取路径
        path_name = os.path.dirname(file_path)
        # 在output_path中创建各级文件夹
        dic_list = re.split(r'[/|\\]',path_name)
        last_dic = output_path
        for idx,dic in enumerate(dic_list):
            last_dic = last_dic+'/'+dic
            if os.path.exists(last_dic):
                pass
            else:
                os.mkdir(last_dic)

        # 以字符串的格式读取java文件
        with open(file_path,'r',encoding='utf-8') as f:
            string = f.read()
        # 按字典替换java字符串
        for key in replace_dict.keys():
            temp_str_list = string.split(key)
            string = '{}'.format(replace_dict[key]).join(temp_str_list)
            if len(temp_str_list)-1!=0:
                count[file_path][key] = len(temp_str_list)-1
        # 写入新字符串到output_path
        with open(output_path+'/'+file_path,'w',encoding='utf-8') as f:
            f.write(string)
    # 写入替换记录
    with open('./replace_count.json','w',encoding='utf-8') as f:
        json.dump(count,f,indent=4)

replace_dict 字典内容

{
"替换前内容": "替换后内容",
"替换前内容": "替换后内容",
"替换前内容": "替换后内容"
}

posted @ 2022-08-26 10:34  小秦的开发梦  阅读(158)  评论(0)    收藏  举报