Just trying to make pickle work, but when I load the file the dictiionary is still empty.
It's an addressbook, with the dictionary keys being names, and values being numbers {N:NUM}
I've programmed pickle to save it to a file with a user specified name, and it does so. I did it in a txt file and could see the data. When I load it after closing the program and rerunning it, the dictionary is still blank. Here's the code:
#Filename: address.py
import pickle
address = {}
def print_menu():
print 'Address Book'
print
print '1. Print contacts'
print '2. Add contact'
print '3. Delete contact'
print '4. Alter contact'
print '5. Save contacts'
print '6. Load contacts'
print '9. Quit'
def add_name(name,number):
address[name] = number
def del_name(name):
if address.has_key(name):
del address[name]
else:
print 'Contact cannot be found.'
def alter_contact(name):
if address.has_key(name):
number = input('New number: ')
address[name] = number
else:
print 'Contact cannot be found.'
def save_contacts(filename,address):
out_file = open(filename, "w")
pickle.dump(address, out_file)
out_file.close()
def load_contacts(filename,address):
in_file = open(filename, "r")
address2 = pickle.load(in_file)
in_file.close()
print_menu()
menu_options = 0
while menu_options != 9:
print
menu_options = input('Type an option: ')
if menu_options == 1:
print address
elif menu_options == 2:
name = raw_input('Name of contact: ')
number = input('Number: ')
add_name(name, number)
elif menu_options == 3:
name = raw_input('Contact to be deleted: ')
del_name(name)
elif menu_options == 4:
name = raw_input('Contact to be updated :')
alter_contact(name)
elif menu_options == 5:
filename = raw_input('Filename to save as: ')
save_contacts(filename,address)
elif menu_options == 6:
filename = raw_input('Filename to load: ')
load_contacts(filename,address)
elif menu_options != 9:
print_menu()
print 'Goodbye'
What is the problem?