扶余市建设局网站,站长统计幸福宝下载,注册一个网站要多少费用,logo查询网站用python实现多文件多文本替换功能
今天修改单位项目代码时由于改变了一个数据结构名称#xff0c;结果有几十个文件都要修改#xff0c;一个个改实在太麻烦#xff0c;又没有搜到比较靠谱的工具软件#xff0c;于是干脆用python手撸了一个小工具#xff0c;发现python在…用python实现多文件多文本替换功能
今天修改单位项目代码时由于改变了一个数据结构名称结果有几十个文件都要修改一个个改实在太麻烦又没有搜到比较靠谱的工具软件于是干脆用python手撸了一个小工具发现python在这方面确实方便代码也就几十行这里记录一下需要的朋友请拿走。 有个需要注意的地方就是文件的编码方式要替换成您文件的编码方式我这里是utf-8windows文件有可能是gbk。
import os
import fileinput# 定义一个函数用于替换文件中的字符串
def replace_in_file(file_path, old_str, new_str):for line in fileinput.input(file_path, inplaceTrue, encodingutf-8):print(line.replace(old_str, new_str), end)fileinput.close()if __name__ __main__:# 设置要替换的目录路径directory D\\dir\\subdir# 设置要替换的字符串字典map)placeDic {oldstring1:newstring1, oldstring2:newstring2, oldstring3:newstring3}old_strings placeDic.keys()# 遍历目录下的所有文件for filename in os.listdir(directory):# 只处理需要的文件if filename.endswith(.cpp):file_path os.path.join(directory, filename)for old_string in old_strings:new_string placeDic.get(old_string, );replace_in_file(file_path, old_string, new_string);