多级菜单(增强版)
1 #__Author__ oliver 2 #__Date__ 2016/8/26 3 4 5 with open('省市县','r',encoding='utf-8') as f_read: 6 data = f_read.readlines() #将文件内容放入大列表 7 # data = f_read.read() #直接读出字符串 8 zone = eval(''.join(data)) #获取地区字典 9 current_layer = dict(zone) 10 parent_layer = [] 11 while True: 12 for key in current_layer: 13 print(key) 14 choice = input("Press <a> Add,press <m> Modify,press <d> Delete;press <b> back,press <q> Quit.\n>>>:").strip() 15 if len(choice) == 0: 16 continue 17 if choice in current_layer: 18 parent_layer.append(current_layer) 19 current_layer = current_layer[choice] 20 if current_layer == {}: 21 print("已到最后一级。") 22 elif choice == 'b': 23 if parent_layer: 24 current_layer = parent_layer.pop() 25 elif choice == 'q': 26 while parent_layer != []: 27 current_layer = parent_layer.pop() 28 break 29 elif choice == 'a': # add操作 30 new_item = input("请输入新地区>>>").strip() 31 if new_item in current_layer: 32 print("地区%s已存在,请重新输入。\n"%new_item) 33 else: 34 new_dic = {} 35 current_layer.setdefault(new_item,new_dic) #增加菜单 36 elif choice == 'd': 37 del_item = input("请输入删除项>>>") 38 if del_item in current_layer: 39 del current_layer[del_item] #删除菜单 40 else: 41 print("菜单中没有'%s'地区!\n"%del_item) 42 elif choice == 'm': 43 modify_item = input("请输入修改项>>>").strip() 44 save_value = current_layer[modify_item] #保存用户输入的key对应的value 45 modify_key = input("请输入新地区>>>").strip() 46 del current_layer[modify_item] 47 modify_dic = {modify_key : save_value} #新键值对 48 current_layer.update(modify_dic) #将新的键值对添加到字典中 49 else: 50 print("无此项!\n") 51 with open('省市县_new','w',encoding='utf-8') as f_write: 52 f_write.write(str(current_layer))
posted on 2016-08-28 14:26 oliver.lee 阅读(262) 评论(0) 编辑 收藏 举报