info文件中的内容为:
{
"河北省": {"石家庄": {"无极县":"", "高邑县":"", "灵寿县":"", "行唐县":"", "元氏县":""},
"唐山市": {"乐亭县":"", "迁西县":"", "滦南县":"", "丰润区":"", "古冶区":""},
"邯郸市": {"大名县":"", "临漳县":"", "邯郸县":"", "肥乡县":"", "永年县":""},
"保定市": {"高阳县":"", "容城县":"", "望都县":"", "安新县":"", "顺平县":""}
},
"河南省": {"郑州市": {"中原区":"", "二七区":"", "金水区":"", "惠济区":"", "管城区":""},
"开封市": {"龙亭区":"", "鼓楼区":"", "顺河区":"", "祥符区":"", "通许县":""},
"安阳市": {"安阳县":"", "汤阴县":"", "内黄县":"", "文峰区":"", "北关区":""},
"新乡市": {"红旗区":"", "卫滨区":"", "牧野区":"", "凤泉区":"", "卫辉市":""}
},
"湖北省": {"武汉市": {"武昌区":"", "汉阳区":"", "江岸区":"", "江夏区":"", "洪山区":""},
"襄阳市": {"宜城市":"", "枣阳市":"", "樊城区":"", "襄州区":"", "南漳县":""},
"宜昌市": {"当阳市":"", "点军区":"", "西陵区":"", "猇亭区":"", "伍家岗":""},
"黄冈市": {"黄州区":"", "麻城市":"", "武穴市":"", "罗田县":"", "团风县":""},
},
}
1 f = open("info","r+",encoding="utf8") 2 a = eval(f.read()) # a点没用 3 menu = dict(a) 4 current_layer = menu # 为了动态循环,初始值为menu 5 f.close() 6 parent_layer = [] # 记录下父层,若是用一个变量来保存则back时,会原地返回 7 8 while True: 9 a = list(sorted(current_layer)) # 排序key保证每次都一样的排序 10 for i,key in enumerate(a,1): 11 print(i,">>>",key) # 循环打印当前层的key 12 chioce = input("输入序号 [q]退出 [b]返回([more]进入管理选项:)").strip() 13 if len(chioce) == 0:continue # 什么都没输入的时候,在打印当前层的信息 14 if chioce.isdigit(): 15 chioce = int(chioce) 16 if 0 < chioce <= len(a): 17 parent_layer.append(current_layer) # * 在当前层还是子层时记录下来 因为马上它要变成父亲了 18 current_layer = current_layer[a[chioce-1]] # 为了下一次的循环将当前层换成用户输入的下一层 19 if not current_layer: # 此时当前层为空 20 print("已经是最后一级菜单") 21 elif chioce == "b": # 这一段的代码是防止回到最上一层时发生错误 22 if parent_layer: # 判断父层记录器是空(False)时,表示回到第一层了,回到while继续打印第一层 23 current_layer = parent_layer.pop() # 若是有东西时(Ture)时,原先记录的本层删除了,然后上面执行上一次记录的父层。 24 elif chioce == "more": 25 chioce_m = input("[a]添加当前信息 [d]删除当前信息 [q]退出") 26 if chioce_m =="a": 27 a_add = input("输入想添加的信息:") 28 current_layer.update({a_add:{}}) # 添加的是字典的嵌套,这样下次添加时仍旧是字典嵌套 29 elif chioce_m == "d": 30 a_del = int(input("输入序号")) 31 del current_layer[a[a_del-1]] 32 else: 33 print("无此项") 34 save_m = input("是否保存当前修改的信息?y or n:") # 加在这个if语句中的好处是只有more的操作后才会提示保存 35 if save_m == "y": 36 menu_str = str(menu) 37 f_m = open("info", "w", encoding="utf8") 38 f_m.write(menu_str) # 保存的方式是以写的模式打开,类似于刷新。 39 elif save_m == "n": 40 pass 41 else: 42 print("无此项") 43 elif chioce == "q": 44 break 45 else: 46 print("无此项")