ImportOS, sys, PyperclipImportEasygui as GImportRefile_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 () whilePattinchold_lines:tes= [I forI, XinchEnumerate (Old_lines)ifx = =Patt] [0] forIinchRange (6): del(Old_lines[tes]) forIinchTarget_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)
ImportOS, sys, PyperclipImportEasygui as GImportRefile_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; }}" "#Turn target into a listwith 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')#Find the location of the textPposi=0posi=0posil=0str_posilist=[]line_posilist=[]#def find_posi (pposi):#Posi=old_text.find (Pat,pposi)#Posil = old_text.count (' \ n ', 0, posi)#return Posi,posil#Turn the code into a listWith open (file_name,'R', encoding='Utf-8') as Rrf:old_lines=Rrf.readlines ()#While posi! =-1:#print (line_posilist)#line-->[3 , +,----#Pposi-->[28, 215, 402, 588, 768,-1]#posi, Posil = Find_posi (posi)s_posilist=[]posil_lis=[] whilePosi!=-1: Posi=Old_text.find (patt,pposi) Posil= Old_text.count ('\ n', 0, posi) Pposi=posi+1s_posilist.append (posi) posil_lis.append (Posil) posil_lis.pop () Posil_lis.pop ()Print(Posil_lis) forKinchPosil_lis:start=k+1#Remove a function segment other than void Test (void) \ n forIinchRange (5): Old_lines.remove (Old_lines[start])#Insert Target_code #revert to Stringold_text="'. Join (old_lines) old_text=old_text.replace (patt,target_code,1) New_text=old_textPrint(New_text) with open (New_file,'W', encoding='Utf-8') as Wf:wf.write (new_text)# over this
Python remove () error may occur