python 电话簿简单代码

#address book
import cPickle
def getkey ():
key = raw_input ('put in name: ')
return key
def insert ():
global x
key = getkey()

if key in x:
  print 'insert error. Name already exist.'
else:
  val = raw_input ('put in address : ')
  x[key] = val
  print 'insert  with address [%s] successful.' % (key, val)
def update ():
global x
key = getkey()
if key in x:
  val = raw_input ('put in address : ')
  x[key] = val
  print 'update  with address [%s] successful.' % (key, val)
else:
  print 'update error. Name is not exist.'
def delete ():
global x
key = getkey()
if key in x:
  del x[key]
  print 'delete  successful.' %key
else:
  print 'delete error. Name is not exist.'
def showall ():
global x

print 'name  ----------  address'
for key, val in x.iteritems():
  print '  ----------  [%s]' %(key, val)
print '|there are %d item(s) in the book.>' %len(x)
def clear ():
global x
x.clear ()
def myhelp ():
        print 'command:'
        print '    insert:   insert name that not in the book.'
        print '    delete:   delete name that exist in the book.'
        print '    update:   update name that exist in the book.'
        print '    showall:  show all name in the book.'
        print '    help:     show the command infomation.'
        print '    clear:    clear the book, the book will be empty.'
        print '    quit:     exit the application.'
version = 1.0
f = file ('address.dat', 'w+')
size = f.tell()
f.close ()
if size == 0:
        x = {}
else:   
        x = cPickle.load (open('address.dat', 'r'))
while True:
cho = raw_input ('Book->')
if cho == 'insert':
  insert ()
elif cho == 'delete':
  delete ()
elif cho == 'update':
  update ()
elif cho == 'showall':
  showall ()
elif cho == 'clear':
  clear ()
elif cho == 'help':
                myhelp ()
elif cho == 'quit' :
  break
else:
  print 'unknow command.'
cPickle.dump (x, open('address.dat','w'))
print 'Bye!'