def delete(ps):
    import os
    filename = ps[-1]
    delelemetns = ps[1]
    with open(filename, encoding='utf-8') as f_read,\
        open('tmp.txt', 'w', encoding='utf-8') as f_write:
        for line in iter(f_read.readline, ''):
            if line != '\n':  # 处理非空行
                if delelemetns in line:
                    line = line.replace(delelemetns,'')
                f_write.write(line)
    os.remove(filename)
    os.rename('tmp.txt',filename)


def add(ps):
    filename = ps[-1]
    addelemetns = ps[1]
    with open(filename, 'a', encoding='utf-8') as fp:
        fp.write("\n", addelemetns)

def modify(ps):
    import os
    filename = ps[-1]
    modify_elemetns = ps[1]
    with open(filename, encoding='utf-8') as f_read, \
            open('tmp.txt', 'w', encoding='utf-8') as f_write:
        for line in iter(f_read.readline, ''):
            if line != '\n':  # 处理非空行
                if modify_elemetns in line:
                    line = line.replace(modify_elemetns, '')
                f_write.write(line)
    os.remove(filename)
    os.rename('tmp.txt', filename)


def search(cmd):
    filename = cmd[-1]
    pattern = cmd[1]
    with open(filename, 'r', encoding="utf-8") as f:
        for line in f:
            if pattern in line:
                print(line, end="")
        else:
            print("没有找到")

dic_func ={'delete': delete, 'add': add, 'modify': modify, 'search': search}

while True:
    inp = input("请输入您要进行的操作:").strip()
    if not inp:
        continue
    cmd_1 = inp.split()
    cmd = cmd_1[0]
    if cmd in dic_func:
        dic_func[cmd](cmd_1)
    else:
        print("Error")