[Tutor] pickle problems
eryksun
eryksun at gmail.com
Sun Aug 12 06:51:49 CEST 2012
On Sat, Aug 11, 2012 at 11:19 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>
>> To clarify, you can store multiple pickles in a file, but each needs
>> its own load. So you'd have to maintain a session dictionary for the
>> factors of new integers. Then append the pickled session to the file
>> when the user quits. When the program starts you'd have to loop
>> through the file to update D with each pickled session.
>
> Isn't that essentially what my script does?
On line 69 your script (http://pastebin.com/SNwKRuSK) appends the
current D to the end. So only the last pickle appended would be
complete. My first response was for you to switch to 'wb' mode to
truncate the file and only save the latest complete session.
Then it occurred to me that you actually wanted to grow the pickle the
file. I proposed the above solution to append the new factorizations
per session. Then at the start load the pickled sessions in a loop,
updating D with each loaded dictionary. For example:
D = {}
session = {}
try:
with open('factors.dat', 'rb') as f:
while True:
D.update(pickle.load(f))
except EOFError:
pass
except (IOError, pickle.PickleError):
D = {}
if len(D):
print("Loaded", len(D), "entries.")
while True:
n = int(input("integer: "))
if n == 0:
print("D has", len(D), "entries.")
with open('factors.dat', 'ab') as f:
pickle.dump(session, f)
break
try:
factors = D[n]
print("the factors of", n, "are", factors)
except KeyError:
factors = factorsOfInteger(n)
print("the factors of", n, "are", factors)
D[n] = factors
session[n] = factors
More information about the Tutor
mailing list