[Tutor] Saving Data

don arnold darnold02 at sprynet.com
Tue Dec 30 15:00:46 EST 2003


----- Original Message -----
From: "moore william" <red_necks25 at yahoo.com>
To: "don arnold" <darnold02 at sprynet.com>
Sent: Tuesday, December 30, 2003 1:26 PM
Subject: Re: [Tutor] Saving Data


> Thanks, will this work with a phone book application
> to save names and nubers?

<snip>
Sure. Basically, you attempt to load your variable from the shelve, modify
it, then save it back to the shelve.

Here's some quick (and not too pretty code):

import shelve

s = shelve.open('c:/temp2/mydata')

if s.has_key('phonebook'):
    phonebook = s['phonebook']
else:
    phonebook = {}

while 1:
    print
    print
    print '1. Enter a phone number'
    print '2. Show all numbers'
    print '3. Quit'
    print
    choice = int(raw_input('Enter your choice: '))

    if choice == 1:
        name = raw_input('Name : ')
        phone = raw_input('Phone: ')
        phonebook[name] = phone
    elif choice == 2:
        print
        for name, phone in phonebook.items():
            print '%-20s : %-14s' % (name, phone)
    elif choice == 3:
        break

##save phonebook when done
s['phonebook'] = phonebook

s.close()


[First run to get some data in the phonebook:]

C:\Python22\mystuff>c:\python22\python shelf2.py


1. Enter a phone number
2. Show all numbers
3. Quit

Enter your choice: 1
Name : Don Arnold
Phone: 402-123-4567


1. Enter a phone number
2. Show all numbers
3. Quit

Enter your choice: 1
Name : John Smith
Phone: 301-596-9384


1. Enter a phone number
2. Show all numbers
3. Quit

Enter your choice: 1
Name : Bob Davis
Phone: 495-030-3030


1. Enter a phone number
2. Show all numbers
3. Quit

Enter your choice: 2

John Smith           : 301-596-9384
Bob Davis            : 495-030-3030
Don Arnold           : 402-123-4567


1. Enter a phone number
2. Show all numbers
3. Quit

Enter your choice: 3

[Second run to show data was saved:]

C:\Python22\mystuff>c:\python22\python shelf2.py


1. Enter a phone number
2. Show all numbers
3. Quit

Enter your choice: 2

John Smith           : 301-596-9384
Bob Davis            : 495-030-3030
Don Arnold           : 402-123-4567


1. Enter a phone number
2. Show all numbers
3. Quit

Enter your choice: 3

C:\Python22\mystuff>


HTH,
Don

PS: Be sure to hit 'Reply All' when responding to Tutor emails. That way,
everyone on the list has a chance to contribute to the discussion.




More information about the Tutor mailing list