Python 三級菜單 省 市 縣 實現

[root@tieba delete]# vim /tmp/content.txt //添加一些內容


{

    '北京':{

           '海淀區':{

                     '三環':{},

                     '四環':{}

           },

           '朝陽區':{

                     '三環':{},

                     '四環':{}

           }

    }

}



腳本內容


/* ---示例代碼----*/
 
#!/usr/bin/env python
# -*- coding:utf-8 -*-
 
CONTENT = '/tmp/content.txt'
 
with open(CONTENT) as fd:
    menu = eval(fd.read().strip())
 
current_layer = menu
parent_layers = []
exit_flag = False
 
while not exit_flag:
    for key in current_layer:
        print key
    choice = raw_input(">>>")
    if choice in current_layer:
        parent_layers.append(current_layer)
        current_layer = current_layer[choice]
    elif choice == 'b':
        if parent_layers:
            current_layer = parent_layers.pop()
        else:
            print "最上層了"
    elif choice == 'a':
        add = raw_input("增加>>>")
        current_layer[add] = ''
        print "add %s Succeed" % add
    elif choice == 'c':
        change = raw_input("修改>>>")
        add    = raw_input("填寫>>>")
        current_layer.pop(change)
        current_layer[add] = ''
        print "%s修改爲%s" % (change,add)
    elif choice == 'd':
        delete = raw_input("刪除>>>")
        if delete in current_layer:
            current_layer.pop(delete)
            print "delete %s Succeed" % delete
        else:
            print "Not found %s" % delete
    elif choice == 'q':
        with open(CONTENT,'w') as fd:
            fd.write(str(menu))
        exit_flag = True
    else:
        print "無此項"
 
/* ---示例代碼----*/



可以添加城市,修改城市,刪除等功能

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章