版权声明:by DongBao https://blog.csdn.net/aaaadong/article/details/81117224
将学习中的例子传上来(省市县三级,简单增删查)
# coding:utf8
'''
Created on 2018/7/19
@author:wshh
'''
shengshixian = open('shengshixian','r',encoding='utf8')
for i in shengshixian:
i=eval(i)
# print(type(i))
current_layer = i
parent_layer = i
parent_layers = []
while True:
for key in current_layer:
print(key)
shengshixiantemp = open('shengshixiantemp', 'w', encoding='utf8')
shengshixiantemp.write(str(current_layer))
shengshixiantemp.close()
choice = input(">>>:").strip()
if len(choice) == 0: continue
if choice in current_layer:
# parent_layer = current_layer
parent_layers.append(current_layer)
current_layer = current_layer[choice]
elif choice == 'b':
# current_layer = parent_layer
if parent_layers:
current_layer = parent_layers.pop()
elif choice == 'c':
# current_layer = parent_layer
choice = input("添加>>>:").strip()
current_layer[choice]={}
elif choice == 'd':
# current_layer = parent_layer
choice = input("删除>>>:").strip()
del current_layer[choice]
elif choice == 'e':
if current_layer == i:
break
else:
print("请输入b返回顶级菜单,才能退出>>>:")
else:
print("无此项")
shengshixian.close()
#shengshixian2 = open('shengshixian', 'w', encoding='utf8')
with open('shengshixiantemp',encoding='utf8') as f,open('shengshixian','w',encoding='utf8') as s:
for i in f:
i = eval(i)
print(i)
s.write(str(i))
其中shengshixian文件如下
{'内蒙古': {'呼和浩特': {'赛罕区': {}}}, '北京': {'朝阳': {'望京': {}, '国贸': {'万达': {}}, '三里屯': {}}, '海淀': {'西三旗': {}, '圆明园': {}, '西二旗': {}}}, '天津': {'红桥': {'丁字沽': {}, '天津西站': {}}, '南开': {'南开大学': {}, '南开医院': {}}}}
运行效果如图
完整项目如下
https://download.csdn.net/download/aaaadong/10551569