python1988

import os

def search(data): #查询
    print(\'查询功能%s\'%data)
    ret=[]
    backend_data=\'backend %s\'%data
    with open (\'test2\',\'r\') as read_test2:
        tag=False
        for read_line in read_test2:
            if read_line.strip()==backend_data:#去除/n与/t
                tag=True
                continue#注意格式对齐
            if read_line.startswith(\'backend\') and tag:
                break
            if tag:
             # print(read_line,end=\'\') #将所有下面的都打印出来
                ret.append(\'%s\n\'%read_line.strip())  #增加\n增加换行
    return ret





def add(data):#增加
    print(\'增加功能=%s\'%data)

def change(data):#修改
    # print(\'修改功能将更改为%s\'%data)
    print(\'用户输入的是%s\'%data)
    backend=\'backend %s\'%data[0]
    res=search(data[0])
    print(\'来自change函数查询到内容\', res)
    if not res :
        return \'查询到记录不存在\'
    else:
        res.append(data[1]+\'\n\')
        print(res)

    res.insert(0,\'%s\n\'%backend)  #第一行增加backend sxj
    with open(\'test2\',\'r\') as read_f,\
            open (\'test3\',\'w\') as write_f:
        tag=False
        has_write=False
        for read_line in read_f:
            if read_line.strip()==backend :
                tag=True
                continue
            if tag and read_line.startswith(\'backend\'):
                tag=False
            if not tag:
                write_f.write(read_line)
            else:
                if not has_write:
                    for record in res:
                        write_f.write(record)
                    has_write=True#用状态的变化控制流程
    os.rename(\'test3\',\'test2_new\')#更改文件名





def delete(data):#删除
    print(\'删除功能:删除%s\'%data)

if __name__==\'__main__\': #一个规范python中只写功能,执行语句放到if判断下面
    msg=\'\'\'
    1:查询
    2:添加
    3:修改
    4:删除
    5:退出
    \'\'\'
    func_dic={
        \'1\':search,
        \'2\':add,
        \'3\':change,
        \'4\':delete
    }
    while True:
        print(msg)
        choice=input("请输入选项:").strip()#strip默认去除空格与回车
        if not choice:continue #如果为空则继续循环打印msg
        if choice==\'5\':break#如果选择5 退出,则break

        data=input(\'请输入data:\').strip()#input输入的是字符串

        if choice != \'1\':#用户输入的都是字符串 VIP
            data=eval(data)  #如果输入的是字典则自动转化

        res=func_dic[choice](data)
        print(\'最终结果是》》》》\',res)

 

 

 

分类:

技术点:

相关文章: