[Tutor] Address book sort of

Jacob S. keridee at jayco.net
Thu Dec 16 03:36:12 CET 2004


Hey, I made some changes to my address book, with help from.... Oh darn,
well whoever you are, I haven't forgotten the help you gave me in changing
my if/if/if/if/if/else things into mapping objects.... Anyway, if anybody
wants a look, here it is.
P.S. I made some changes to the file reading part too. Got rid of some
unnecessary code.


[start]
from os.path import exists as ex

tel = {}
tempname = "Telephone.cfg"
if not ex(tempname):
    open(tempname,"w").close()
file = open(tempname,"r")
stuff = file.read()
file.close()
if stuff == '':
    a = 1
    print "No entries on file."
else:
    tel = eval(stuff)
    a = 0

print """\
Commands are:
add
get
save
delete
quit
all is a wildcard
"""

def dispatch(command,entity,tel):
    tfunct = functs[command]
    tfunct(entity,tel)

def add(person,tel):
    if tel.has_key(person):
        print "That person is already in there. If you wish to edit the
file, please delete the record first."
    else:
        tel[person] = raw_input("What is their phone number? ")

def get(person,tel):
    if a == 1:
        print "Sorry, there are no entries available."
    else:
        if person == 'all':
            key = tel.keys()
            key.sort()
            print
            for x in key:
                print "%s\n%s\n" % (x,tel[x])
        elif tel.has_key(person):
            print "\n%s\n%s\n" % (person,tel[person])
        else:
            print "%s is not in your records." % person

def delete(person,tel):
    if not a:
        if person == 'all':
            tel={}
            open('Telephone.cfg', 'w').close()
        else:
            if tel.has_key(person):
                del tel[person]
            else:
                print "%s is not in your records." % person
    else:
        print "There is no one to delete."

def save(entitynotneeded,tel):
    file=open('Telephone.cfg', 'w')
    file.write(str(tel))
    file.close()
    print 'Saved in Telephone.cfg'

functs = {'add':add,'get':get,'save':save,'delete':delete}

while 1:
    ask = raw_input('Tell me what you wish to do. ')
    if ask == "quit":
        break
    ask = ask.split(" ")
    command = ask[0]
    entity = " ".join(ask[1:])
    if entity == '' and command != 'save':
        entity = raw_input("Who do you want to %s? " % command)
    dispatch(command,entity,tel)

file = open('Telephone.cfg', 'w')
file.write(str(tel))
file.close()
[end]

Jacob Schmidt



More information about the Tutor mailing list