[Tutor] how to create a persistent dictionary w/ cpickle?
Carter Danforth
carter.danforth at gmail.com
Wed Sep 8 19:43:42 CEST 2010
Hi, I'm trying to a create a basic addressbook for practice. I'm using a
dictionary with cpickle, though I'm not sure how to persistently store each
instance in the dictionary. Below is the code I have so far.
If I run it once and add a contact and the details, it's fine. p.load(f)
shows the details next time I run it, but if I add another contact, and run
it again, the previous key:value doesn't show. It gets replaced by the new
one.
How can I fix this so that it adds the new key:value to the dictionary
instead of replacing the existing one? Appreciate any help, thanks.
import cPickle as p
addressbook = 'addressbook.data'
f = file(addressbook, 'r+')
class address:
def __init__(self, name, tel, email):
self.name = name
self.tel = tel
self.email = email
ab = {self.name : self.tel}
f = file(addressbook, 'r+')
p.dump(ab, f)
print p.load(f)
x = raw_input()
if x == 'add':
name = raw_input('\nName: ')
tel = raw_input('Tel: ')
email = raw_input('Email: ')
contact = address(name, tel, email)
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20100908/0f8588ad/attachment.html>
More information about the Tutor
mailing list