首页 > 代码库 > 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()有可能会出现错误