还没有写完准备弡上cpickle 还有字典
#!/usr/bin/python #Filename: cpickle.py import cPickle as p import os shoplistfile="shoplist.data" storedlist={} def menu(): running=True try: while running: try: f=file(shoplistfile) storedlist=p.load(f) command=raw_input("Please input command: ") if command=="help": help() elif command=="add": add(storedlist) elif command=="delete": delete(storedlist) elif command=="update": update(storedlist) elif command=="select": select(storedlist) elif command=="quit": running=False elif command=='show': show(storedlist) else: print "ERROR, please input help!" finally: f.close() else: print "Done" except EOFError: print "QUIT" except KeyboardInterrupt: print "Q" finally: print "DONE" def show(storedlist): print '-'*40 for (k,v) in storedlist.items(): print '%s \t'%k,v print '-'*40 def add(storedlist): try: username=raw_input("Please input add username:") # print storedlist # print username if(storedlist.has_key(username)): print "Username Exist!!" return 0 emailbox=raw_input("Please input add email:") storedlist[username]=emailbox except: print "err add" finally: write(storedlist) def select(storedlist): try: username=raw_input("Please input select username:") if storedlist.has_key(username): print storedlist[username] else: print 'Username not find!!' return 0 except: print "err select" finally: write(storedlist) def delete(storedlist): try: username=raw_input("Please input delete username:") if storedlist.has_key(username): print storedlist[username] else: print 'Username not find!!' return 0 storedlist.pop(username) except: print "err delete" finally: write(storedlist) def update(storedlist): try: #not key ? username=raw_input("Please input update username:") if storedlist.has_key(username): print storedlist[username] else: print 'Username not find!!' return 0 emailbox=raw_input("Please input update email:") storedlist[username]=emailbox except: print "err update" finally: write(storedlist) def write(stored): f=file(shoplistfile,'w') p.dump(stored,f) f.close() def index(): if os.path.exists(shoplistfile): menu() else: print 'Contacts not find!' print 'Create Contacts...' create_con() def create_con(): shoplist={} try: f=file(shoplistfile,'w') p.dump(shoplist,f) except IOError: print 'find not file!!' finally: f.close() menu() def help(): """ ------------------------ ==>>help ==>>add < username email > ==>>delete < username > ==>>update < username newemail > ==>>select < username > ==>>quit ------------------------""" print help.__doc__ if __name__=='__main__': index()
练习字典,看简明的python后面有一个练习,根据cPickle 写一个通讯录,恶心下自己!