zoukankan      html  css  js  c++  java
  • Python之旅的第13天(功能的练习)

    突然看到关于习题的部分,要求是为文件实现查询、添加、修改、删除、退出等功能

    先出现自己的弱爆了的版本吧!

    # 需要实现对一个文件的查询、添加、修改、删除、和退出
    # 日常写Python文件的时候在正式执行的文件前面应该加上 if __name__ = '__main__'
    # 用于区分,这样别人在调用文件的时候就不会将这些需要执行的部分进行执行了
    # 首先应写出文件功能框架,再加入对应方法的代码
    # 函数练习、文件解耦、tag的引入
    import os
    def fetch(data):   #定义查询函数
        print('这是查询功能')
        print('查询的内容是:',data)
        backend_data = 'backend %s'%data
        res = []
        with open('ceshi','r') as read_f:
            tag = False
            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:
                    print(read_line,end = '')
                    res.append(read_line)
        return res
    
    def add():     #定义添加函数
        pass
    
    def change(data):   #定义修改方法
        print('用户输入的内容是>>>',data)
        backend = data[0]['backend']      #获得列表中输入的字典一个值www.oldboy20.org
        backend_data = 'backend %s'%backend
    
        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'],)
        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(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_data)
        with open('ceshi','r') as read_f,
                open('ceshi_new','w') as write_f:
            tag = False
            has_write = True
            for read_line in read_f:
                if read_line.strip() == backend_data:
                    tag = True
                    continue
                if tag and read_line.startswith('backend'):
                    break
                if not tag:
                    write_f.write(read_line)
                else:
                    if has_write :
                        for record in res:
                            write_f.write(record)
        os.rename('ceshi','ceshi1')
        os.rename('ceshi_new','ceshi')
        os.remove('ceshi1')
    
    
    def delete():   #定义删除方法
        pass
    
    def exit():     #定义退出
        pass
    
    if __name__ == '__main__':
        msg = '1.查询' 
              '2.添加' 
              '3.修改' 
              '4.删除' 
              '5.退出' 
              '6.其他操作'
    
        menu_dic = {
            '1': fetch,
            '2': add,
            '3': change,
            '4': delete,
            '5': exit
        }
    
        while True:
            print(msg)
            choice = input('请选择操作>>>').strip()
            if len(choice) == 0 or choice not in menu_dic:
                continue
            if choice == 5:
                break
    
            data=input("数据>>: ").strip()
    
            #menu_dic[choice](data)==fetch(data)
            if choice != '1':
                data=eval(data)
            res = menu_dic[choice](data) #add(data)
            print(res)

    紧接着是按照视频中讲授的内容,对文件做了一定的解耦之后发生的神奇变化。

    #_*_coding:utf-8_*_
    import os
    def file_handle(filename,backend_data,record_list=None,type='fetch'): #type:fetch append change
        new_file=filename+'_new'
        bak_file=filename+'_bak'
        if type == 'fetch':
            r_list = []
            with open(filename, 'r') as f:
                tag = False
                for line in f:
                    if line.strip() == backend_data:
                        tag = True
                        continue
                    if tag and line.startswith('backend'):
                        break
                    if tag and line:
                        r_list.append(line.strip())
                for line in r_list:
                    print(line)
                return r_list
        elif type == 'append':
            with open(filename, 'r') as read_file, 
                    open(new_file, 'w') as write_file:
                for r_line in read_file:
                    write_file.write(r_line)
    
                for new_line in record_list:
                    if new_line.startswith('backend'):
                        write_file.write(new_line + '
    ')
                    else:
                        write_file.write("%s%s
    " % (' ' * 8, new_line))
            os.rename(filename, bak_file)
            os.rename(new_file, filename)
            os.remove(bak_file)
        elif type == 'change':
            with open(filename, 'r') as read_file, 
                    open(new_file, 'w') as write_file:
                tag=False
                has_write=False
                for r_line in read_file:
                    if r_line.strip() == backend_data:
                        tag=True
                        continue
                    if tag and r_line.startswith('backend'):
                        tag=False
                    if not tag:
                        write_file.write(r_line)
                    else:
                        if not has_write:
                            for new_line in record_list:
                                if new_line.startswith('backend'):
                                    write_file.write(new_line+'
    ')
                                else:
                                    write_file.write('%s%s
    ' %(' '*8,new_line))
                            has_write=True
            os.rename(filename, bak_file)
            os.rename(new_file, filename)
            os.remove(bak_file)
    
    def fetch(data):
        backend_data="backend %s" %data
        return file_handle('haproxy.conf',backend_data,type='fetch')
    def add(data):
        backend=data['backend']
        record_list=fetch(backend)
        current_record="server %s %s weight %s maxconn %s" %(data['record']['server'],
                                                             data['record']['server'],
                                                             data['record']['weight'],
                                                             data['record']['maxconn'])
        backend_data="backend %s" %backend
    
        if not record_list:
            record_list.append(backend_data)
            record_list.append(current_record)
            file_handle('haproxy.conf',backend_data,record_list,type='append')
        else:
            record_list.insert(0,backend_data)
            if current_record not in record_list:
                record_list.append(current_record)
            file_handle('haproxy.conf',backend_data,record_list,type='change')
    def remove(data):
        backend=data['backend']
        record_list=fetch(backend)
        current_record="server %s %s weight %s maxconn %s" %(data['record']['server'],
                                                             data['record']['server'],
                                                             data['record']['weight'],
                                                             data['record']['maxconn'])
        backend_data = "backend %s" % backend
        if not record_list or current_record not in record_list:
            print('33[33;1m无此条记录33[0m')
            return
        else:
            #处理record_list
            record_list.insert(0,backend_data)
            record_list.remove(current_record)
            file_handle('haproxy.conf',backend_data,record_list,type='change')
    def change(data):
        backend=data[0]['backend']
        record_list=fetch(backend)
    
        old_record="server %s %s weight %s maxconn %s" %(data[0]['record']['server'],
                                                             data[0]['record']['server'],
                                                             data[0]['record']['weight'],
                                                             data[0]['record']['maxconn'])
    
        new_record = "server %s %s weight %s maxconn %s" % (data[1]['record']['server'], 
                                                            data[1]['record']['server'], 
                                                            data[1]['record']['weight'], 
                                                            data[1]['record']['maxconn'])
        backend_data="backend %s" %backend
    
        if not record_list or old_record not in record_list:
            print('33[33;1m无此内容33[0m')
            return
        else:
            record_list.insert(0,backend_data)
            index=record_list.index(old_record)
            record_list[index]=new_record
            file_handle('haproxy.conf',backend_data,record_list,type='change')
    def qita(data):
        pass
    
    
    if __name__ == '__main__':
        msg='''
        1:查询
        2:添加
        3:删除
        4:修改
        5:退出
        6:其他操作
        '''
        menu_dic={
            '1':fetch,
            '2':add,
            '3':remove,
            '4':change,
            '5':exit,
            '6':qita,
        }
        while True:
            print(msg)
            choice=input("操作>>: ").strip()
            if len(choice) == 0 or choice not in menu_dic:continue
            if choice == '5':break
    
            data=input("数据>>: ").strip()
    
            #menu_dic[choice](data)==fetch(data)
            if choice != '1':
                data=eval(data)
            menu_dic[choice](data) #add(data)

    真的是需要深刻理解,后面的内容还是比较多的,就不能继续看下去了,就跟今天吃饭一样,搞多了反而拉肚子了。

  • 相关阅读:
    增强型window.showModalDialog弹出模态窗口数据传递高度封装实验 西安
    谈谈Asp.net网站优化二:关于 服务器控件 和 客户端控件(html标签)的选择 西安
    谈谈Asp.net网站优化一:SqlDataReader和DataSet的选择 西安
    我2年来整理的.NET开发类库源代码共享 西安
    类似baidu google分页器效果的代码(修改于 kwklover 同学基础上) 西安
    C#.NET动手开发域名抢注前检测工具。 西安
    解决vs2008 项目文件(b/s)右键“在浏览器中打开”出现两个浏览器 西安
    基于Json的Ajax无刷新分页效果实现(一) 西安
    基于Json的Ajax无刷新分页效果实现(二) 西安
    循环冗余检验 (CRC) 算法原理
  • 原文地址:https://www.cnblogs.com/xiaoyaotx/p/12431780.html
Copyright © 2011-2022 走看看