withopen(file_path, "r", encoding='UTF-8') as file_in, open("out-"+file_path, "w", encoding='UTF-8') as file_out: line = file_in.readline() while line: # 获取所有匹配的Match对象 matched1 = patter1.finditer(line) matched2 = patter2.finditer(line) pos_list = [] if matched1 != None: pos_list += [(x.start("tar"), x.end("tar")) for x inlist(matched1)] if matched2 != None: pos_list += [(x.start("tar"), x.end("tar")) for x inlist(matched2)] pos_list.sort() # 按开始位置从小到大排序 for v in pos_list[::-1]: # 逆序遍历 st, ed = v # 替换掉原来的 if st == ed: line = line[:st] + prefix + line[st:] else: line = line[:st] + prefix + line[ed:] file_out.write(line); line = file_in.readline()