Reputation: 1
I am currently trying to learn Python and having learned the basics I decided to try to make an address book program. I am having trouble loading the contacts after they have been saved though. Here's what I have so far,
import pickle
contacts = {}
class Contact:
def __init__(self, name, phone, address):
self.name = name
self.phone = phone
self.address = address
Name = input('Contacts Name - ')
Phone = input('Phone Number - ')
Address = input('Address - ')
contacts[Name] = Contact(Name, Phone, Address)
with open('SaveFile', 'wb') as f:
pickle.dump(contacts, f)
this all seems to work fine and the contacts dictionary is saved but when I try to load the contacts back after I have cleared the dictionary it does not work for some reason,
def load():
with open('SaveFile', 'rb') as f:
contacts = pickle.load(f)
I don't get an error message but the dictionary stays empty. Any help with this would be much appreciated!
Upvotes: 0
Views: 104
Reputation: 298226
Variables have scope. The contacts
variable you assigned to within the load
function has no relationship to the contacts
you defined as a global variable. The simplest solution would be to make your function return
the newly loaded contacts, letting you replace the existing dictionary:
def load_contacts():
with open('SaveFile', 'rb') as f:
new_contacts = pickle.load(f)
return new_contacts
...
contacts = load_contacts()
If you do want to directly access the global contacts
variable from within the load
function, you can use the global
keyword to tell Python that you're referring to contacts
from the global scope:
def load():
global contacts
with open('SaveFile', 'rb') as f:
contacts = pickle.load(f)
You could also avoid assigning to your global contacts
and instead modify it:
def load():
contacts.clear()
with open('SaveFile', 'rb') as f:
new_contacts = pickle.load(f)
contacts.update(new_contacts)
The difference in the last example is that you're directly working with the object referred to by contacts
.
Upvotes: 1