• 【练习】Python第四次:实现对文件的增删改查


    一,实现对文件的增删改查

    (一),三级菜单的处理结构及退出技巧:使用TAG标记

    tag=True
    while tag:
        print('leve1')
        choice=input("level1>>: ").strip()
        if choice == 'quit':break
        if choice == 'quit_all': tag = False
        while tag:
            print('level2')
            choice = input("level2>>: ").strip()
            if choice == 'quit': break
            if choice == 'quit_all': tag = False
            while tag:
                print('level3')
                choice = input("level3>: ").strip()
                if choice == 'quit': break
                if choice == 'quit_all': tag = False

    (二),查询功能实现,编写fetch函数

    def fetch(data):
        print('这是查询功能')
        print('用户数据是',data)
        backend_data ='backend %s' %data
        with open('haproxy.conf','r') as read_f:
            tag = False #找到标志
            ret =[]
            for read_line in read_f:
                if read_line.strip() == backend_data:#匹配到数据
                    tag = True
                    continue
                if tag and read_line.startswith('backend'):#到下一个backend停止
                    break
                if tag:  #找到后读出后面的数据
                    print('%s' %read_line,end ='')
                    ret.append(read_line)
        return ret
    
    def add():
        pass
    
    def change():
        pass
    
    def delete():
        pass
    
    #Python文件里面只写不会运行的功能,测试代码在下面写
    if __name__ == '__main__':
        msg='''
        1:查询
        2:添加
        3:修改
        4:删除
        5:退出
        '''
        msg_dic ={
            '1':fetch,
            '2':add,
            '3':change,
            '4':delete,
        }
    
        while True:
            print(msg)
            choice = input('请输入你的选项:').strip()
            if not choice:continue
            if choice == '5':
                break
            data = input('请输入你的数据:').strip()
            res = msg_dic[choice](data)
            print(res)

    (三)修改功能实现,添加change函数

    import os #os包含改名和删除文件函数
    def fetch(data):
        # print('这是查询功能')
        # print('用户数据是',data)
        backend_data ='backend %s' %data
        with open('haproxy.conf','r') as read_f:
            tag = False #找到标志
            ret =[]
            for read_line in read_f:
                if read_line.strip() == backend_data:#匹配到数据
                    tag = True
                    continue
                if tag and read_line.startswith('backend'):#到下一个backend停止
                    break
                if tag:  #找到后读出后面的数据
                    print('%s' %read_line,end ='')
                    ret.append(read_line)
        return ret
    
    def add():
        pass
    
    # [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]
    def change(data):
        # print('这是修改功能')
        # print('用户输入数据是:',data)
        backend = data[0]['backend'] #从用户传参提取www.oldboy1.org
        backend_line = 'backend %s' %data[0]['backend']#内容:backend www.oldboy1.org
    
        #拼接字符串old_server_record,把用户传参的源server信息整理出来
        old_server_record = '%sserver %s %s weight %s maxconn %s
    ' %(' '*8,data[0]['record']['server'],
                                                                    data[0]['record']['server'],
                                                                    data[0]['record']['weight'],
                                                                    data[0]['record']['maxconn'])
        #用户传参的目标server信息
        new_server_record = '%sserver %s %s weight %s maxconn %s
    ' %(' '*8,data[1]['record']['server'],
                                                                    data[1]['record']['server'],
                                                                    data[1]['record']['weight'],
                                                                    data[1]['record']['maxconn'])
        print('用户想要修改的记录是:', old_server_record)
        res = fetch(backend)
        print('来自change函数结果--》',res)
    
        if not res or old_server_record not in res:
            return '你要修改的记录不存在'
        else:
            index = res.index(old_server_record)
            res[index] = new_server_record
    
        res.insert(0,'%s
    ' %backend_line)
        with open('haproxy.conf','r') as read_f,
            open('haproxy.conf_new','w') as write_f:
            tag = False
            has_write = False
            for read_line in read_f:
                if read_line.strip() == backend_line:
                    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('haproxy.conf', 'haproxy.conf.bak')
        os.rename('haproxy.conf_new','haproxy.conf')
        os.remove('haproxy.conf.bak')
    
    def delete():
        pass
    
    #Python文件里面只写不会运行的功能,测试代码在下面写
    if __name__ == '__main__':
        msg='''
        1:查询
        2:添加
        3:修改
        4:删除
        5:退出
        '''
        msg_dic ={
            '1':fetch,
            '2':add,
            '3':change,
            '4':delete,
        }
    
        while True:
            print(msg)
            choice = input('请输入你的选项:').strip()
            if not choice:continue
            if choice == '5':
                break
            data = input('请输入你的数据:').strip()
            if choice != '1': #查询输入的是字符串,其他需要处理格式化数据
                data = eval(data)
            res = msg_dic[choice](data)
            print('最终结果是————》',res)

    (四)函数解耦,把fetch函数和change函数中对文件的处理部分提取到file_handler函数

    import os #os包含改名和删除文件函数
    def file_handler(backend_data,res = None,type='fetch'):
        if type == 'fetch':
            with open('haproxy.conf', 'r') as read_f:
                tag = False  # 找到标志
                ret = []
                for read_line in read_f:
                    if read_line.strip() == backend_data:  # 匹配到数据
                        tag = True
                        continue
                    if tag and read_line.startswith('backend'):  # 到下一个backend停止
                        break
                    if tag:  # 找到后读出后面的数据
                        print('%s' % read_line, end='')
                        ret.append(read_line)
            return ret
        elif type == 'change':
            with open('haproxy.conf', 'r') as read_f, 
                    open('haproxy.conf_new', 'w') as write_f:
                tag = False
                has_write = False
                for read_line in read_f:
                    if read_line.strip() == backend_data:
                        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('haproxy.conf', 'haproxy.conf.bak')
            os.rename('haproxy.conf_new', 'haproxy.conf')
            os.remove('haproxy.conf.bak')
    
    
    def fetch(data):
        # print('这是查询功能')
        # print('用户数据是',data)
        backend_data ='backend %s' %data
        return file_handler(backend_data)
    
    def add():
        pass
    
    # [{'backend':'www.oldboy1.org','record':{'server':'2.2.2.4','weight':20,'maxconn':3000}},{'backend':'www.oldboy1.org','record':{'server':'2.2.2.5','weight':30,'maxconn':4000}}]
    def change(data):
        # print('这是修改功能')
        # print('用户输入数据是:',data)
        backend = data[0]['backend'] #从用户传参提取www.oldboy1.org
        backend_line = 'backend %s' %data[0]['backend']#内容:backend www.oldboy1.org
    
        #拼接字符串old_server_record,把用户传参的源server信息整理出来
        old_server_record = '%sserver %s %s weight %s maxconn %s
    ' %(' '*8,data[0]['record']['server'],
                                                                    data[0]['record']['server'],
                                                                    data[0]['record']['weight'],
                                                                    data[0]['record']['maxconn'])
        #用户传参的目标server信息
        new_server_record = '%sserver %s %s weight %s maxconn %s
    ' %(' '*8,data[1]['record']['server'],
                                                                    data[1]['record']['server'],
                                                                    data[1]['record']['weight'],
                                                                    data[1]['record']['maxconn'])
        print('用户想要修改的记录是:',old_server_record)
        res = fetch(backend)
        print('来自change函数结果--》',res)
    
        if not res or old_server_record not in res:
            return '你要修改的记录不存在'
        else:
            index = res.index(old_server_record)
            res[index] = new_server_record
    
        res.insert(0,'%s
    ' %backend_line)
        file_handler(backend_line,res=res,type='change')
    
    
    def delete():
        pass
    
    #Python文件里面只写不会运行的功能,测试代码在下面写
    if __name__ == '__main__':
        msg='''
        1:查询
        2:添加
        3:修改
        4:删除
        5:退出
        '''
        msg_dic ={
            '1':fetch,
            '2':add,
            '3':change,
            '4':delete,
        }
    
        while True:
            print(msg)
            choice = input('请输入你的选项:').strip()
            if not choice:continue
            if choice == '5':
                break
            data = input('请输入你的数据:').strip()
            if choice != '1': #查询输入的是字符串,其他需要处理格式化数据
                data = eval(data)
            res = msg_dic[choice](data)
            print('最终结果是————》',res)
  • 相关阅读:
    bzoj 3091 城市旅行(LCT+数学分析)
    bzoj 2843 极地旅行社(LCT)
    Tsinsen A1303. tree(伍一鸣) (LCT+处理标记)
    bzoj 2002 [Hnoi2010]Bounce 弹飞绵羊(LCT)
    bzoj 2049 [Sdoi2008]Cave 洞穴勘测(LCT)
    vijos P1213 80人环游世界(有源汇的上下界费用流)
    bzoj 3698 XWW的难题(有源汇的上下界最大流)
    bzoj 2502 清理雪道(有源汇的上下界最小流)
    sgu 176 Flow construction(有源汇的上下界最小流)
    详解 $_SERVER 函数中QUERY_STRING和REQUEST_URI区别
  • 原文地址:https://www.cnblogs.com/fudonghai/p/10346057.html
Copyright © 2020-2023  润新知