函数优化
# -*- 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
# 三级菜单,省市县,增删改查
def write_file(old,new):
with open('data','w') as write_file:
write_file.write(str(parrent_layer[0]).replace(old,new))
write_file.flush()
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)
write_file(before,after)
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)
write_file(before,after)
else:
print('无法删除不存在键')
elif choice == 'e':
# 修改
before = input('修改:')
after = input('改为:')
current_layer[after] = current_layer.pop(before)
write_file(before,after)
elif choice == 'q':
break
else:
print('不存在')