省市县三级菜单,增删改查,文件存储 data字典文件
{'天津': {'经开区': {'经开东区': {4}, '经开西区': {4}}, '天津市': {'河东区': {4}, '河西区': {4}, '南开区': {4}, '河北区': {4}, '和平区': {4}}}, '北京': {'北京市': {'丰台区': {4}, '朝阳区': {4}, '东城区': {4}, '西城区': {4}}}}main.py
# -*- coding: utf-8 -*- # @Author: oppend # @Date: 2017-07-31 21:00:25 # @Last Modified by: oppend # @Last Modified time: 2017-08-02 22:08:46 # 三级菜单,省市县,增删改查 parrent_layer = {} with open('data','r') as read_file: menu = eval(read_file.read().strip()) current_layer = menu layer_num = 0 while True: for province in current_layer: print(province) choice = input('[b]上级[a]增加[d]删除[e]修改[q]退出:') if choice in current_layer: parrent_layer[layer_num] = current_layer layer_num += 1 current_layer = current_layer[choice] elif choice == 'b': if parrent_layer: layer_num -= 1 current_layer = parrent_layer.pop(layer_num) else: print('已经是最上级') elif choice == 'a': add_choice = input('增加:') before = str(current_layer) current_layer[add_choice] = {} after = str(current_layer) with open('data','w') as write_file: write_file.write(str(parrent_layer[0]).replace(before,after)) write_file.flush() elif choice == 'd': del_choice = input('删除:') before = str(current_layer) if del_choice in current_layer: del current_layer[del_choice] after = str(current_layer) with open('data','w') as write_file: write_file.write(str(parrent_layer[0]).replace(before,after)) write_file.flush() else: print('无法删除不存在键') elif choice == 'e': # 修改 before = input('修改:') after = input('改为:') current_layer[after] = current_layer.pop(before) with open('data','w') as write_file: write_file.write(str(parrent_layer[0]).replace(before,after)) write_file.flush() elif choice == 'q': break else: print('不存在')