[Tutor] (no subject)
Steven D'Aprano
steve at pearwood.info
Thu Feb 9 12:28:32 CET 2012
ken brockman wrote:
> I have been trying to post all afternoon to no avail. I keep getting
> bounced back...
Ken, I don't suppose you have another email address that you sometimes use?
Because if you do, that may be the problem.
If you are subscribed to this list as krush1954 at yahoo.com, and you try to send
to it using another email address, you will get bounced. The list software can
only recognize you by your email address.
> def General_info():
> file4 = open("Genfacts.p", "rb")
This line above is the problem: it tries to open a file which may not exist.
> Ginfo = pickle.load(file4)
> file4.close()
> print('General Information: ')
> GinfoKey = input('CatKey: ')
> GinfoFact = input('Info: ')
> Ginfo[GinfoKey] = GinfoFact # add new key:fact
> file4 = open("Genfacts.p", "wb")
> pickle.dump(Ginfo, file4)
> file4.close()
> return(Ginfo)
Try this instead:
def General_info():
try:
file4 = open("Genfacts.p", "rb")
Ginfo = pickle.load(file4)
file4.close()
except IOError:
# Either the file doesn't exist, or something more serious.
# Assume the file doesn't exist.
Ginfo = {} # Start with an empty dict.
print('General Information: ')
GinfoKey = input('CatKey: ')
GinfoFact = input('Info: ')
Ginfo[GinfoKey] = GinfoFact # add new key:fact
file4 = open("Genfacts.p", "wb")
pickle.dump(Ginfo, file4)
file4.close()
return Ginfo
Note: Python experts will probably point out a whole bunch of things I did
wrong in the above. That's deliberate: I didn't want to overload you with too
many changes all at once.
By the way, the shelve module is specifically designed to solve the problem
you are trying to solve here: how to store key:value pairs on disk. Here's a
version using shelve:
import shelve
def get_facts():
facts = shelve.open('facts.db', writeback=True)
print('Please enter a fact: ')
key = input('CatKey: ')
value = input('Info: ')
facts[key] = value
# Make a copy for later use.
d = {}
d.update(facts) # Copy from facts --> d
facts.close()
return d
Good luck!
--
Steven
More information about the Tutor
mailing list