[Tutor] writing & reading files
Frank Holmes
flash1210@hotmail.com
Wed, 16 Jan 2002 12:25:59 -0800
Still working with this little phonebook program. When it runs, if
'phoneyold' doesn't exist it creates it and writes data to file. Problem is,
if I close the program, open it again and again add entries it overwrites
the file and none of the previous entries exist. I have tried replacing the
'w' in f=open('phoneyold','w') with 'a' to append to the file (problem is it
is a dictionary) but although when I check the data file the entry is there,
I cannot retrieve it. I have also tried 'w+' to append, but again all
previous data is dumped when I add. Again I am stumped. How can I add data,
close the file, re open it , add again and not dump previous data?
import pickle
def add_name():
print 'Enter Name:'
dname=raw_input()
print 'Facility:'
fname=raw_input()
print 'phone1:'
hnum=raw_input()
if hnum == " " : #in no huntline entered, hunt =NONE
hnum='none'
print'phone2:'
ph=raw_input()
print 'Pager:'
pg=raw_input()
print 'cell:'
cop=raw_input()
print 'Comments:'
com=raw_input()
l=(dname, fname, hnum, ph, pg, cop, com)
d1[dname]=l
f=open('phoneyold','w')
pickle.dump(d1,f)
f.close()
def get_name():
print "enter name to search"
name=raw_input()
f=open('phoneyold','r')
p_d1=pickle.load(f)
if name in p_d1.keys():
g= p_d1[name]
print 'Name:', g[0]
print
print 'place:', g[1]
print
print 'phone1:', g[2]
print
print 'Phone2:',g[3]
print
print 'Pager:', g[4]
print
print 'cell:', g[5]
print
print 'Comments:',g[6]
f.close()
d1={}
while 1:
print
print "Hello, welcome to Docsearch."
print
print "Please enter selection:"
print "Type '1' to search"
print
print "Type '2' to add name to database or 'quit' to exit"
_________________________________________________________________
Send and receive Hotmail on your mobile device: http://mobile.msn.com