Python基础-----实现文件的增删改查

实现文件的增删改查

 1 #!/usr/bin/env python
 2 # -*- coding:utf-8 -*-
 3 import os
 4 def file_handler(backend_data,res = None,type = 'fetch'):   #文件处理函数
 5     if type == 'fetch':   #查询操作
 6         with open('haproxy.conf','r') as read_f:
 7             tag = False           #初始状态标识
 8             ret = []              #用于放置查询结果
 9             for read_line in read_f:
10                 if read_line.strip() == backend_data:  #用strip()去除读取的末尾回车、空格
11                     tag = True
12                     continue  #查询到需要查询的数据则继续执行下次循环
13                 if tag and read_line.startswith('backend'):break #防止跳到下一条记录(以backend开头的)
14                 if tag:
15                     print(read_line,end = '')
16                     ret.append(read_line)
17             else:
18                 print('未查询到你所要找的记录!')
19         return ret
20     elif type == 'change':
21         with open('haproxy.conf','r') as read_f,\
22             open('haproxy.conf_new','w') as write_f: #因为文件没有修改一说,所以相当于创建副本
23             tag = False  #状态标识
24             has_write = False  #用于标记已经写入的内容
25             for read_line in read_f:
26                 if read_line.strip() == backend_data:
27                     tag = True
28                     write_f.write('%s\n'%backend_data)   #写入需要修改的backend标题
29                     continue
30                 if tag and read_line.startswith('backend'): #防止跳到下一条记录(以backend开头的)
31                     tag = False  #遇到其他backend记录,不会出现修改
32                 if not tag:   #尚未读取到需要修改的部分,则直接读写
33                     write_f.write(read_line)
34                 else:
35                     if not has_write:
36                         for record in res:
37                             write_f.write(record)
38                         has_write = True   #将修改的内容全部写好,则改变已经写入的状态
39         os.rename('haproxy.conf','haproxy.conf.bak')  #将原文件备份为备份文件
40         os.rename('haproxy.conf_new','haproxy.conf')  #覆盖原文件
41 def fetch(data): #查询
42     print('查询的数据为:%s'%data)
43     backend_data = 'backend %s' %data         #拼接出关键词
44     return file_handler(backend_data)
45 
46 
47 def add(data): #添加
48     pass
49 def change(data): #修改
50     backend = data[0]['backend']  #文件中的一条记录www.oldboy1.org,需要修改,先执行查找,如果没有,则不能修改
51     backend_data = 'backend %s'%backend   #backend www.oldboy1.org
52     old_server_record = '%sserver %s weight %s maxconn %s\n'%(
53                                                             ' '*8,data[0]['record']['server'],
54                                                             data[0]['record']['weight'],
55                                                             data[0]['record']['maxconn'],
56                                                             )
57     new_server_record = '%sserver %s weight %s maxconn %s\n'%(
58                                                         ' '*8,data[1]['record']['server'],
59                                                         data[1]['record']['weight'],
60                                                         data[1]['record']['maxconn'],
61                                                         )
62     print('用户想要修改的记录是:',old_server_record)
63     res = fetch(backend)   #返回指定backend记录的列表
64     if not res or old_server_record not in res:  #没找到(1 backend没找到 2 server没找到)
65         return '你要修改的记录不存在!'
66     else:
67         index = res.index(old_server_record)
68         res[index] = new_server_record   #获取到修改的值列表
69     return file_handler(backend_data,res = res , type = 'change')
70 def delete(): #删除
71     pass
72 
73 
74 if __name__ == '__main__':   #执行可执行的语句
75     msg = '''
76         1:查询
77         2:添加
78         3:修改
79         4:删除
80         5:退出
81     '''
82     msg_dic = {
83         '1' : fetch,
84         '2' : add,
85         '3' : change,
86         '4' : delete
87     }
88     while True:
89         print(msg)
90         choice = input('请输入你的选项:').strip()
91         if not choice : continue   #用户输入为空时
92         if choice == '5':break     #输入5则退出程序
93 
94         if choice != '1':
95             data = eval(input('输入数据:').strip())   #有用户输入,并过滤掉前后空格及回车;在修改增加等操作传入的是字典格式
96             fetch_res = msg_dic[choice](data)        #根据选项字典获取函数名,加()则运行相关选项函数
97         else:
98             data = input('输入数据:').strip()  #有用户输入,并过滤掉前后空格及回车;在修改增加等操作传入的是字典格式
99             fetch_res = msg_dic[choice](data)        #根据选项字典获取函数名,加()则运行相关选项函数

 

posted @ 2018-10-03 23:32  Meanwey  阅读(904)  评论(0编辑  收藏  举报