日志格式
backend test.oldboy.orgb1 backend buy.oldboy.org
import json s = '''{"backend":"%s", "record":{ "server":"%s", "weight":"%s", "maxcoon":"%s" } }''' # 显示一级菜单 def p_1(): print('1:增加一条记录',' 2:删除一条记录') # 显示二级菜单 def p_2(): print('1:test.oldboy.org',' 2:buy.oldboy.org') #计算开始和结束位置 def ins_del(readlines): mstart = mend = None for i in readlines: if dic['backend'] in i: mstart = readlines.index(i) elif None != mstart and i.strip() == '': mend = readlines.index(i,mstart) break else: mend = len(readlines) if not ' ' in readlines[mend - 1]:#如果结束行没有换行,就添加换行符 readlines[mend - 1] += ' ' return mstart,mend while True: p_1() pt = input('选择增加还是删除:') if pt == 'q': print('退出操作') exit() elif pt.isdigit() and int(pt) > 0 and int(pt) < 3: p_2() if int(pt) == 1:#增加 while True: pt = input('选择要增加的类型:') if pt == 'q': print('退出操作') exit() elif pt == 'b': break elif pt.isdigit() and int(pt) > 0 and int(pt) < 3: server = input('输入server信息:') weight = input('输入weight信息:') maxcoon = input('输入maxcoon信息:') if int(pt) == 1: ts = s % ('test.oldboy.org',server,weight,maxcoon) else: ts = s % ('buy.oldboy.org',server,weight,maxcoon) dic = json.loads(ts)#将字典格式字符串转换成字典(字符串内需用双引号) with open('file.txt','r+') as f: r = f.readlines() mstart,mend = ins_del(r) r.insert(mend, (' server {server} weight {weight} maxcoon {maxcoon} '.format(**dic['record']))) f.seek(0)#readlines后指针的文件尾部,所以要移动指针到首部 f.writelines(r)#新增比原来行数多,会直接覆盖,所以不用清空原文件 break #跳出此次操作 else: print('未定义%s' % pt) else:#删除 while True: pt = input('选择要删除的类型:') if pt == 'q': print('退出操作') exit() elif pt == 'b': break elif pt.isdigit() and int(pt) > 0 and int(pt) < 3: with open('file.txt','r') as f: r = f.readlines() if int(pt) == 1: dic = {"backend": "test.oldboy.org",} else: dic = {"backend": "buy.oldboy.org",} mstart,mend = ins_del(r) tlist = list(r[mend:mstart:-1])#倒序切片列表 rcount = 1#倒序步进值,因为mend=空行或列表总行数,比实际下标多1,所以从1开始 for i in tlist: if 'server' in i:#判断是否是要删除的内容 #内容是倒的,所有查找索引也要从倒着开始,不然index默认找第一次出现的值 r.pop(r.index(i,mend - rcount)) break rcount += 1 with open('file.txt','w') as f:#清空原始文本 f.writelines(r) break else: print('未定义%s' % pt) else: print('未定义%s' % pt)