python練習題1優化:用戶信息保存到文件

需求:app

控制檯根據用戶選擇實現:spa

     一、添加用戶(個別信息必填)add usercode

     二、展現用戶列表 list userblog

     三、根據名字搜索用戶信息 search userinput

     四、根據名字修改用戶信息 modify userit

     五、退出 exitclass

 def add_user():
    filename=raw_input("你想保存到的文件名稱爲:")
    fo=open(filename,"a")
    print "請輸入保存信息內容:"
    
    choise="y"
    while choise=="y":
        userdict={}
        userlist=[]
        name=raw_input("name:")
        age=raw_input("age:")
        sex=raw_input("sex:")
        phone=raw_input("phone:")
        userlist.append(age)
        userlist.append(sex)
        userlist.append(phone)
        userdict[name]=userlist
        content=str(userdict)
        fo.write(content+'\n')        
        choise=raw_input("是否繼續?y/n:")
    fo.close()
    print "保存成功"
    return filename

def list_user():
    filename=raw_input("你想查看的文件名稱爲:")
    print "如下爲全部學員信息:"
    fo=open(filename,"r")
    content=fo.readlines() 
    for dic in content:
        userdict=eval(dic)
        name=userdict.keys()[0]
        age=userdict.values()[0][0]
        sex=userdict.values()[0][1]
        phone=userdict.values()[0][2]
        print "-"*20
        print "name:", name
        print "age:",age
        print "sex:",sex
        print "phone:",phone   
    fo.close()


def search_user():
    filename=raw_input("你想搜索的文件名稱爲:")
    fo=open(filename,"r")
    content=fo.readlines()
   
    search_name=raw_input("你想查詢信息的名字爲:")
    for dic in content:
        userdict=eval(dic)
        if search_name in userdict.keys()[0]:
            age=userdict.values()[0][0]
            sex=userdict.values()[0][1]
            phone=userdict.values()[0][2]
            print "-"*20
            print "age:",age
            print "sex:",sex
            print "phone:",phone
    fo.close()

def modify_user():
    filename=raw_input("你想修改的文件名稱爲:")
    fo=open(filename,"r")
    content=fo.readlines() 
    modify_name=raw_input("你想修改信息的名字爲:")
    for index, dic in enumerate(content):
        userdict=eval(dic)
        if userdict.keys()[0]==modify_name:
            choise=int(raw_input("你想修改的信息爲(0爲年齡,1爲性別,2爲電話):"))
            newcontent=raw_input("你想修改成:")
            userdict.values()[0][choise]=newcontent
            print "修改爲功!"
            content[index]=userdict  
            break
    contentdict=content
    fo=open(filename,"w")        
    for i in contentdict:
        i=str(i)
        fo.write(i+'\n')
    fo.close()


def choice():
  
    print"\n"
    print "作一個選擇:1,增長用戶,2,用戶列表,3,搜索用戶,4,修改用戶,5,退出!"
    print"\n"
    
    choice=raw_input("請作選擇:")
    if choice=="1":
        add_user()
    elif choice == "2":
        list_user()
    elif choice=="3":
        search_user()
    elif choice=="4":
        modify_user()
    elif choice=="5":
        print'DONE!'
        exit()
    else:
        print "請輸入1-5之間的整數:"     
choice()
相關文章
相關標籤/搜索