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 字典内容

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


__EOF__

本文作者华哥哥
本文链接https://www.cnblogs.com/rainbow--/p/16626733.html
关于博主:评论和私信会在第一时间回复。或者直接私信我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,可以点击文章右下角推荐一下。您的鼓励是博主的最大动力!
posted @   小秦的开发梦  阅读(147)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
点击右上角即可分享
微信分享提示