Reputation: 1
I am new to python and am trying to teach myself how to program in python through the us of codecademy. But in my own time I decided to attempt to program a phone book using dictionaries and the pickle function i read about on this forum. But in experimenting with pickle to save my dictionary for the phone book itself the code kept raising an "EOFError" I have no idea what this is or how to solve it. So, if anyone is able to help me i would really appreciate it
#My Code
import pickle
PhoneBook = {}
reloaded = {}
with open("C:\\Programming\\Phone Book.txt", "rb") as inf: #Modify this dependent on where the file is located
reloaded = pickle.load(inf)
def help():
print "add_contact('name', 'number') - Adds a new contact to your phone book."
print "display_phone_book() - Displays the contents of your phone book."
print "display_contact('name') - Displays the resident of your phone book with the corrosponding name."
def add_contact(name, number):
PhoneBook [name] = number
with open("C:\\Programming\\Phone Book.txt", "wb") as outf: #Modify this dependent on where the file is located
pikle.dump(PhoneBook, outf)
def display_phone_book():
print PhoneBook
def display_contact(name):
print "%s's phone number is:" %(name)
print PhoneBook[name]
#Error's Code:
def load_eof(self):
raise EOFError
dispatch[''] = load_eof
Upvotes: 0
Views: 519
Reputation: 365627
It's hard to tell without seeing the actual code that demonstrates the problem, or the error, or how you're using it, but…
The first time you run your program, there's nothing in PhoneBook.txt
. Either the open
or the pickle.load
is going to fail. And since you can't even get past the first few lines of the first run of the program, there's no way the problem will ever get fixed; you'll just keep getting the same failure forever.
If that's your problem, you probably want something like this:
try:
with open("C:\\Programming\\Phone Book.txt", "rb") as inf:
reloaded = pickle.load(inf)
except (IOError, EOFError) as e:
print('Failed to find old data ({!r}), creating new'.format(e))
reloaded = {}
You might want to restrict the cases that are automatically handled a bit (e.g., on IOError, if it's EACCES
instead of ENOENT
, don't try to just ignore the error and move on) or expand them (e.g., if the file isn't empty, but is corrupted, you might get a KeyError
instead of an EOFError
). If you're not sure what you want, it may be best to start with except Exception as e:
, come up with a bunch of test cases, see what you get for each one, and decide which ones should make the program fail and which ones should be handled by just starting from scratch.
Upvotes: 1