Delete the line of the specified content in the document & delete if it contains the same element

1. Equal content will be deleted

    def my_delete(self,target_line):

        del_path=r'img/my_data/cord.txt'       #待删除内容存放地址

        with open(del_path, 'r', encoding='utf-8') as f:
            l=f.readlines()
        f.close()

        '''去掉标签中换行符'''
        lines=[]
        for i in l:
            lines.append(i.rstrip())

        ge=target_line      #列表==》每个元素是删除内容

        new=''      #存放被删除后的内容
        for i,line in enumerate(lines):
            mode =True         #记录两个值是否相等
            '''两个内容进行比较'''
            for j in ge:
                if j in line:
                    mode = False
                    break
            if mode:
                new += line+'\n'
        '''将被删除后的内容写入原路径文档'''
        with open(del_path,'w',encoding='utf-8') as f:
            f.writelines(new)

2. If it contains the same element, delete it

Add a loop to traverse each character in each line of the content to be deleted

del_path=r'./img/123.txt'
with open(del_path,'r',encoding='utf-8')as f:
    l = f.readlines()

lines=[]
for i in l:
    lines.append(i.rstrip())

ge = ['Beyond','黄家驹']
new = ''
for line in lines:
    mode = True
    for i in ge:
        for j in line:
            if i in line:
                mode = False
                break
    if mode:
        new += line+'\n'

with open(del_path,'w',encoding='utf-8')as f:
    f.writelines(new)

Guess you like

Origin blog.csdn.net/qq_43586192/article/details/111533072