python⽂件实现增删改查操作 1# coding = utf-8
2
3import os
4import json
5import re
6'''
7本程序旨在将练习基础知识部分,包括:
8列表,元组,字典,⽂件,函数,字符串等知识
9实现的功能:
101.查询
112.删除
123.更改
134.增加
14'''
15
16#定义的⽂档存储格式
17 mes_style = '''bankend
18 server 192.168.50.21 wight 100 maxconn 300
19bankend
20 server 192.168.99.31 wight 50 maxconn 100\n
21'''
22
23#⽤户只能修改这些字段的值
24 updateable ={
25 1:"server",
26 2:"wight",
27 3:"maxconn"
28 }
29
30#菜单
31 menu_info = '''
321.查询
332.删除
343.修改
354.添加
365.退出
37'''
38
39
40
41#展⽰菜单
42def show_menu():
43'''
44 to display the menu ,I chosed the str to show it
45
46'''
47print(menu_info)
48
49#初始化操作,往⽂件⾥边添加格式⽂件
50def before_start():
51'''
52 before start,you can call this func to create a file
53 and then you should explanatory(注释) this method before calling
54 the main method
55'''
56 f = open("web.property","a+",encoding="utf-8")
57for i in mes_style:
58 f.writelines(i)
59 f.close()
60#before_start()
61#查询记录
62def search(user_enter):
63'''
64 this function can be used when search function needed
65 user can select the listed item and then,the corresponding
66 entry will be display
67'''
68#查询并打印出⽤户查询关键字所在的⾏和下⼀⾏
69 f = open("web.property","r",encoding="utf-8")
70 list = f.readlines()
71for i,line in enumerate(list):
72if user_enter in line:
73print(line)
74print(list[i+1])
75elif i == len(list)-1:
76print("查⽆结果")
77 f.close()
90
91#查出所有的⽂件内容,并包装成字典返回
92def searchall():
93'''
94 this function is a common function ,it can used in delete and update,so add
95'''
96 f = open("web.property", "r", encoding="utf-8")
97 list = f.readlines()
98#⽤来存储到value为空所对应的key
99 list1 =[]
100 mapc = {}
101for i,line in enumerate(list):
102if line == "\n"or line == "":
103 list.pop(i)
104for i in range(0,len(list),2):
105 mapc[int(i/2)+1] =list[i:i+2]
106 f.close()
107return mapc
108#删除
109def delete():
110'''
111 this function is used to delete the record user selected
112'''
113 flag = True
114while flag:
115 maps = searchall()
116for i in maps.items():
117print(i)
118 user_selected = input("请选择要删除的对象(输⼊b返回):")
119if user_selected.isdigit():
120 user_selected = int(user_selected)
121#print(list)
122for j in maps.keys():
123if user_selected == j:
124 temp = j
125for m in maps.items():
126if user_selected == m:
127 temp = m
128#删除⽂件中对应的该条记录
129for line in list(maps.keys()):
130if temp== line:
131 maps.pop(temp)
132 file_path = "C:/Users/Administrator/PycharmProjects/pythondemo/web.propertybak" 133if ists(file_path):
134 os.remove(file_path)
135 os.renames("web.property", "web.propertybak")
136 f6 = open("web.property", "w")
137for line in maps.values():
138 f6.write(line[0])
139 f6.write(line[1])
140 f6.close()
141break
142else:
143break
144print(maps)
145#询问是否继续
146 conti = input("是否继续删除?(y/n):")
147if conti == "y":
148continue
149else:
150 flag = False
151break
152elif user_selected == "b":
153break
154else:
155print("输⼊有错误,请重新选择")
156
157
158#添加
159def add():
160'''
161 you can execute add funciton to add a node to file
162 but you should according to those forms
163 1:"server",
164 2:"wight",
165 3:"maxconn"
166'''
167#regs ={"bankend":"www.\w","server":"\d.\d.\d.\d"}
168
169
170while True:
171print("请依次填⼊下列选项中的值")
172 bankend = input("bankend:")
173 server = input("server:")
174 wight = input("wight:")
175 maxconn = input("maxconn:")
176# 正则表达式检查输⼊是否符合格式要求
177if repile(r"www\.(\w+)(\|\|\.org|\)").match(bankend):
178print("bankend ok")
179if repile(r"\d+\.\d+\.\d+\.\d").match(server):
180print("server ok")
181if repile(r"\d").match(wight):
182print("wight ok")
183if repile(r"\d").match(maxconn):
184print("maxconn ok")
185#条件都符合
186 write_date =["bankend %s\n"%bankend," server %s wigth %d maxconn %d"%(server,int(wight),int(maxconn))] 187 f = open("web.property", "a", encoding="utf-8")
188for line in write_date:
189 f.writelines(line)
190 f.close()
191break
192else:
193print("maxconn invalid")
194continue
195else:
196print("wight invalid")
197continue
198else:
199print("server invalid")
200continue
201else:
202print("bankend invalid")
203continue
204
205
206#更新
207def update():
208'''
209 this function is designed for update the file message,content
210'''
211 state = 0
212while True:
213 mapa = searchall()
214for i,m in enumerate(mapa):
215print(str(i+1)+"."+str(mapa[m]))
216 it = input("请选择要更改的条⽬:(b 返回)")
217if it.isdigit():
218 it = int(it)
219for i in mapa.keys():
220if it == i:
221print("check pass")
222while True:
223for member in updateable:
224print(str(member)+":"+updateable[member])
225 user_se = input("请选择要修改的字段(按b返回):")
226if user_se.isdigit():
227 user_se =int(user_se)
228for j in updateable.keys():
229if user_se == j:
230print("check pass2")
231while True:
232 update_to = input("请输⼊值:")
233if update_to==None or update_to=="":
234pass
235else:
236break
237print(user_se)
238#获得选择的字段
239 map_attr = updateable[user_se]
240 li =[]
241for l in mapa[it]:
242if map_attr in l:
243 li.append(l.split(""))
244print(l)
245#print(li)
246for i,ind in enumerate(li[0]):
247if(map_attr in ind and map_attr == "server"):
248 ind = ""+map_attr+""+(str(update_to) if update_to.isdigit() else update_to)
249elif (map_attr in ind ):
250 ind = "" + map_attr + "" + (str(update_to) if update_to.isdigit() else update_to)
251 li[0][i]=ind
252break
253#同步到mapa
254 final_str =""
255for i in li[0]:
256if"server"in i:
257 final_str += ""+i+""
258elif"wight"in i:
259 final_str +=i+""
260else:
261 final_str += i
262#print(final_str)
263for i,n in enumerate(mapa[it]): 264if"server"in n:
265 mapa[it][i] =final_str+"\n" 266print(mapa)
267 with open("web.property","w") as f: 268for line in mapa.values():
writelines使用方法python269 f.writelines(line)
270 f.close()
271print(mapa)
272print(li)
273print("修改成功")
274break
275elif j == len(updateable):
276print("不在选项内,请重新选择") 277elif user_se == "b":
278break
279elif i ==len(mapa):
280print("输⼊选项不在列表中,请重新选择") 281elif it == "b":
282 state = 1
283break
284else:
285print("输⼊有误")
286if state == 1:
287return
288
289#主程序
290while True:
291 show_menu()
292 selected = input("请选择:(1,2,3,4,5):")
293if selected.isdigit():
294 selected = int(selected)
295if selected == 1:
296 search(input("请输⼊要查询的⽹址:"))
297if selected == 2:
298 delete()
299if selected == 3:
300 update()
301if selected == 4:
302 add()
303if selected == 5:
304break
305else:
306print("你输⼊了其他字符,请输⼊数字")
307continue
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论