zoukankan      html  css  js  c++  java
  • 编写程序对文件进行增删改查

    import os
    def fetch(data):
        print('33[1;41m这是查询功能33[0m')
        print('33[1;41m用户数据33[0m', data)
        backend_data = 'backend %s' %data
        with open ('lala.conf', 'r', encoding = 'utf-8') 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'):
                    break
                if tag:
    
                    ret.append(read_line)
    
        return ret
    
    def add():
        pass
    
    def change(data):
        print("这是修改功能")
        backend = data[0]['backend']   #文件中的一条记录 www.oldboy1.org
        backend_data = 'backend %s' %backend
    
        old_service_recode = '%sservice %s %s weight %s maxconn %s
    ' % (' '*8,data[0]['record']['service'],
                                                                         data[0]['record']['service'],
                                                                         data[0]['record']['weight'],
                                                                         data[0]['record']['maxconn'])
    
        new_service_recode = '%sservice %s %s weight %s maxconn %s
    ' % (' ' * 8, data[1]['record']['service'],
                                                                         data[1]['record']['service'],
                                                                         data[1]['record']['weight'],
                                                                         data[1]['record']['maxconn'])
        print('用户想要修改的记录是%s' % old_service_recode)
        res = fetch(backend)
        if not res or old_service_recode not in res:
            return '你要修改的文件不存在'
        else:
            index1 = res.index(old_service_recode)
            res[index1] = new_service_recode
        res.insert(0, '%s
    '%backend_data)
    
        with open('lala.conf', 'r', encoding='utf-8') as read_f, open('lala_new.conf', 'w', encoding = 'utf8') 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('lala.conf', 'sb')
        os.rename('lala_new.conf', 'lala.conf')
        os.remove('sb')
    
    
    
    
    
    
    
    def delete():
        pass
    
    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)
    

      数据输入:[{'backend':'www.oldboy1.org', 'record': {'service':'2.2.2.4','weight':20,'maxconn':30000}},{'backend':'www.oldboy1.org','record': {'service':'2.2.2.5','weight':30,'maxconn':4000}}]

    程序的解耦

    把程序中间复杂的重复代码,封装到一个函数中去

    import os
    def fetch(data):
        print('33[1;41m这是查询功能33[0m')
        print('33[1;41m用户数据33[0m', data)
        backend_data = 'backend %s' %data
        return func(backend_data)
    def func(backend_data, res = None, type = 'fetch'):
        if type == 'fetch':
            with open ('lala.conf', 'r', encoding = 'utf-8') 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'):
                        break
                    if tag:
    
                        ret.append(read_line)
            return ret
        elif type =='change':
            with open('lala.conf', 'r', encoding='utf-8') as read_f, open('lala_new.conf', 'w', encoding='utf8') 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('lala.conf', 'sb')
            os.rename('lala_new.conf', 'lala.conf')
            os.remove('sb')
    
    def add():
        pass
    
    def change(data):
        print("这是修改功能")
        backend = data[0]['backend']   #文件中的一条记录 www.oldboy1.org
        backend_data = 'backend %s' %backend
    
        old_service_recode = '%sservice %s %s weight %s maxconn %s
    ' % (' '*8,data[0]['record']['service'],
                                                                         data[0]['record']['service'],
                                                                         data[0]['record']['weight'],
                                                                         data[0]['record']['maxconn'])
    
        new_service_recode = '%sservice %s %s weight %s maxconn %s
    ' % (' ' * 8, data[1]['record']['service'],
                                                                         data[1]['record']['service'],
                                                                         data[1]['record']['weight'],
                                                                         data[1]['record']['maxconn'])
        print('用户想要修改的记录是%s' % old_service_recode)
        res = fetch(backend)
        if not res or old_service_recode not in res:
            return '你要修改的文件不存在'
        else:
            index1 = res.index(old_service_recode)
            res[index1] = new_service_recode
        res.insert(0, '%s
    '%backend_data)
        func(backend_data,res = res, type = 'change')
    
    
    
    
    
    
    def delete():
        pass
    
    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)
    

      

    一个奋斗中的产品小白
  • 相关阅读:
    RegExp.$1
    Wide&Deep 模型学习教程
    docker 安装与使用的相关问题
    Centos 防火墙
    odoo ERP 系统安装与使用
    Linux 开机自动启动脚本
    intel RDT技术管理cache和memory_bandwidth
    tensorflow 中 inter_op 和 intra_op
    centos 7 安装 nginx 或 apache,及其比较
    Dependency injection in .NET Core的最佳实践
  • 原文地址:https://www.cnblogs.com/dabai123/p/11285822.html
Copyright © 2011-2022 走看看