正则表达式比较复杂,前段时间花了一些时间研究,但一直没能与实际工作结合起来,这几天修改配置文件,因牵涉的文件极其多,逐个修改工作量很大,便考虑写个工具,以后再改就方便了很多,结果就被正则表达式给难住了,原来[]符号在正则中是有特别用处的,一时疏忽,结果搞了好久。
解决的问题如下:程序搜索某个目录下的配置文件,找到后将配置文件的某个session下的列表替换掉。
打算分三步走
1、建立函数replace_session(fileName, sessionName, *alist),用以替换指定文件中,指定sessionName中的内容
2、查找指定目录下的指定文件,得出指定文件列表
3、将1和2组合起来,实现查找文件并替换对应SessionName的功能。
代码如下:
myCode # !usr/bin/env python2.7 # coding: utf-8 # filename: find_replace_ini.py import findfile import replaceIni filelist = findfile.find_file_by_pattern("ipad_set.ini") if(len(filelist) <= 0): print("not find file.") for file in filelist: print(file) replaceIni.replace_session(file, "NOWL2_DEST_SERVERs", "192.168.0.1:25", "192.168.0.3:110")
myCode # !usr/bin/env python2.7 # coding: utf-8 # filename:findfile.py import re import os def find_file_by_pattern(pattern='.*', base=".", circle=True): '''查找给定文件夹下面所有 ''' re_file = re.compile(pattern) if base == ".": base = os.getcwd() final_file_list = [] #print (base) cur_list = os.listdir(base) for item in cur_list: if item == ".svn": continue full_path = os.path.join(base, item) if full_path.endswith(".doc") or \ full_path.endswith(".bmp") or \ full_path.endswith(".wpt") or \ full_path.endswith(".dot"): continue # print full_path bfile = os.path.isfile(item) if os.path.isfile(full_path): if re_file.search(full_path): final_file_list.append(full_path) else: final_file_list += find_file_by_pattern(pattern, full_path) return final_file_list if __name__ == "__main__": filelist = find_file_by_pattern("ipad_set.ini") for file in filelist: print(file)
myCode# !usr/bin/env python 2.7 # coding: utf-8 # filename: replaceIni.py # 替换配置文件中某个session下的字符串数组 import re def replace_session(fileName, sessionName, *alist): pattern = re.compile(r'[[].*[]]') datalist0 = [] datalist1 =[] datalist2 =[] start = 0 file_object = open(fileName, "r") list_of_all_the_lines = file_object.readlines() for line in list_of_all_the_lines: if(line.find("[{0}]".format(sessionName)) != -1): start = 1 elif (re.compile(r'[[].*[]]').search(line)): if(start == 1): start = 2 if(start == 0): datalist0.append(line) if(start == 1): datalist1.append(line) if(start == 2): datalist2.append(line) file_object.close() datalist1_replace = []; if(len(datalist1) > 0): datalist1_replace.append(datalist1[0]) for line in alist: datalist1_replace.append("{0}\n".format(line)) for line in datalist1[1:]: if(re.compile(r'\s*#').match(line)): datalist1_replace.append(line) else: print("not find session, {0}, [{1}]".format(fileName, sessionName )) return file_object = open(fileName, "w") for line in datalist0: file_object.write (line) for line in datalist1_replace: file_object.write (line) for line in datalist2: file_object.write (line) file_object.close() if __name__ == "__main__": replace_session("ipad_set.ini", "NOWL2_DEST_SERVERs", "192.168.0.1:25222", "192.168.0.3:110") print("done")