需求:对文件进行增删改查
由于时间原因,本次代码没有增加任何注释,如有疑问,请联系编辑者:闫龙
其实我也是醉了,看着这些个代码,我脑袋也特么大了,没办法,大神说了,不让用新知识,只可以使用学过的,所以代码复用就不用说了,根本不可能了,希望大家可以看懂这些,别人啃着糟心,自己看着恶心的代码;
优化工作量很大,还未及时进行,还望各位海涵,谢谢!
# 编辑者:闫龙 import os; Menu = ["查询","添加","修改","删除"] while True:for i in range(len(Menu)):print(i+1,Menu[i]);UserSelect = input("请选择您要操作的类型>>>:");if (UserSelect == "1") :TitlesDic = {};count = 0;with open("haproxy.conf", mode="r+", encoding="utf8") as ConfFile:ConfRead = ConfFile.readlines();for i in ConfRead:if (not i[0].isspace()):count += 1;TitlesDic[count] = {};TitlesDic[count][i.strip()] = "";Titles = i.strip();else:TitlesDic[count][Titles] += i;for i in TitlesDic.keys():k = list(dict(TitlesDic[i]).keys())[0]print(i,k);UserSelect = input("请选择您要查询的字段>>>:");for i,j in dict(TitlesDic[int(UserSelect)]).items():print(i+"\n",j);if(UserSelect == "2"):print("目前只能针对bakend字段进行添加操作")bakend = {}com = "backend\t"+input("请输入域名:") + "\n"bakend[com] ="";bakend[com] +=("\tserver\t"+input("Server:")+"\t");bakend[com] +=("weight\t"+input("weight:") + "\t");bakend[com] +=("maxconn\t"+input("maxconn:") + "\n");with open("haproxy.conf",mode="a+") as ConfFile:for i,j in bakend.items():ConfFile.writelines(i+j);print("添加成功!")if(UserSelect == "3"):print("目前只能针对backend www.oldboy20.org字段进行修改操作")bakend = {}WriteDic = {};com = "backend\t"+input("请输入域名:")bakend[com] ="";bakend[com] +=("\tserver\t"+input("Server:")+"\t");bakend[com] +=("weight\t"+input("weight:") + "\t");bakend[com] +=("maxconn\t"+input("maxconn:") + "\n");with open("haproxy.conf", mode="r+", encoding="utf8") as ConfFile:ConfRead = ConfFile.readlines();for i in ConfRead:if (not i[0].isspace()):Titles = i.strip();WriteDic[Titles] ="";else:WriteDic[Titles] += i;with open("haproxy.conf_new",mode="w+",encoding="utf8") as WriteNewFile:WriteDic.pop("backend www.oldboy20.org")WriteDic.update(bakend);for i,j in WriteDic.items():WriteNewFile.writelines(i+"\n"+j);os.rename("haproxy.conf","haproxy.conf_bak");os.rename("haproxy.conf_new", "haproxy.conf");print("修改成功!")if(UserSelect == "4"):TitlesDic = {};WriteDic = {};count = 0;with open("haproxy.conf", mode="r+", encoding="utf8") as ConfFile:ConfRead = ConfFile.readlines();for i in ConfRead:if (not i[0].isspace()):count += 1;TitlesDic[count] = {};TitlesDic[count][i.strip()] = "";Titles = i.strip();WriteDic[Titles] ="";else:TitlesDic[count][Titles] += i;WriteDic[Titles] += i;for i in TitlesDic.keys():k = list(dict(TitlesDic[i]).keys())[0]print(i, k);UserSelect = input("请选择您要删除的字段>>>:");with open("haproxy.conf_new",mode="w+",encoding="utf8") as WriteNewFile:WriteDic.pop(list(dict(TitlesDic[int(UserSelect)]).keys())[0])for i,j in WriteDic.items():WriteNewFile.writelines(i+"\n"+j);os.rename("haproxy.conf","haproxy.conf_bak");os.rename("haproxy.conf_new", "haproxy.conf");print("删除成功");