首页 > 代码库 > python remove()有可能会出现错误
python remove()有可能会出现错误
import os, sys, pyperclip import easygui as g import re file_name = ‘tt3‘ target_code_file = ‘targetcode‘ new_file = ‘new_code2.text‘ replace_code = r‘‘‘void test(void) { int a=10; char s[10]={0}; printf("a=%d,s=%s\n",a,s); } ‘‘‘ pat = replace_code.split(‘\n‘)[0] patt = ‘{:s}{:s}‘.format(pat, ‘\n‘) with open(target_code_file, ‘r‘, encoding=‘utf-8‘) as trf: target_code_list = trf.readlines() with open(file_name, ‘r‘, encoding=‘utf-8‘) as rrf: old_lines = rrf.readlines() target_code_list.append(‘\n‘) target_code_list.reverse() while patt in old_lines: tes = [i for i, x in enumerate(old_lines) if x == patt][0] for i in range(6): del (old_lines[tes]) for i in target_code_list: old_lines.insert(tes, i) old_lines = ‘‘.join(old_lines) print(old_lines) with open(new_file, ‘w‘, encoding=‘utf-8‘) as wf: wf.write(old_lines)
import os, sys, pyperclip import easygui as g import re file_name = ‘tt3‘ target_code_file=‘targetcode‘ new_file=‘new_code.text‘ with open(file_name, ‘r‘, encoding=‘utf-8‘) as rf: old_text = rf.read() replace_code = r‘‘‘void test(void) { int a=10; char s[10]={0}; printf("a=%d,s=%s\n",a,s); } ‘‘‘ target_code=r‘‘‘int func(int a){ int fd=open("/dev/kd_camera_hw",O_RWD); if(fd < 0){ printf("camera open fail\n"); return -1; }else{ printf("camera open success!\n"); return 0; } } ‘‘‘ # 把target变成列表 with open(target_code_file,‘r‘,encoding=‘utf-8‘) as trf: target_code_list=trf.readlines() pat = replace_code.split(‘\n‘)[0] patt=‘{:s}{:s}‘.format(pat,‘\n‘) # 找出文位置 pposi=0 posi=0 posil=0 str_posilist=[] line_posilist=[] # def find_posi(pposi): # posi=old_text.find(pat,pposi) # posil = old_text.count(‘\n‘, 0, posi) # return posi,posil # 把代码变成列表 with open(file_name, ‘r‘, encoding=‘utf-8‘) as rrf: old_lines=rrf.readlines() # while posi != -1: # print(line_posilist) # line-->[3, 17, 31, 45, 59] # pposi -->[28, 215, 402, 588, 768,-1] # posi, posil = find_posi(posi) s_posilist=[] posil_lis=[] while posi!=-1: posi=old_text.find(patt,pposi) posil = old_text.count(‘\n‘, 0, posi) pposi=posi+1 s_posilist.append(posi) posil_lis.append(posil) posil_lis.pop() posil_lis.pop() print(posil_lis) for k in posil_lis: start=k+1 # 删除除void test(void)\n 以外的函数段 for i in range(5): old_lines.remove(old_lines[start]) # 插入target_code # 恢复到字符串 old_text=‘‘.join(old_lines) old_text=old_text.replace(patt,target_code,1) new_text=old_text print(new_text) with open(new_file,‘w‘,encoding=‘utf-8‘) as wf: wf.write(new_text) # over this
python remove()有可能会出现错误
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。