[Tutor] pickle problems

Richard D. Moores rdmoores at gmail.com
Sun Aug 12 04:43:29 CEST 2012


On Sat, Aug 11, 2012 at 6:18 PM, eryksun <eryksun at gmail.com> wrote:
> On Sat, Aug 11, 2012 at 6:30 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>>
>> I wrote pickle_attempt.py as an exercise to try to learn to use the
>> pickle module. See the version I edited for Tutor,
>> pickle_attempt_for_web.py at
>> <http://pastebin.com/SNwKRuSK>.
>> ....
>> But after closing the program and restarting it, those items have
>> disappeared from D.
>
> On line 68 you open the file in 'ab' mode. A pickle stream ends with
> an ASCII period (\x2e). Anything appended after that is ignored. Use
> 'wb' mode. Also, Python 3.x defaults to protocol 3, which is binary,
> so you might want a file extension other than .txt, such as .pkl,
> .dat, .bin, etc.

Changing to 'wb' mode and using the file extension .dat completely
corrected the problems, it seems. Line 69 now reads,
f = open("factors.dat", 'wb')

But the reference I have says of 'wb': "Write to a binary file. If the
file exists, its contents are overwritten. If the file doesn't exist,
it's created. Why doesn't factors.dat get overwritten before the
pickle.dump()? Is it because there isn't any new data to be written at
that point?

And another question, if I might. If factors.dat doesn't exist, to use
the program I need to manually create it and rem out lines 49-52 the
first time I call the script. I thought I could replace lines 49-52
with

===========
if "factors.dat":
    f = open("factors.dat", 'rb')
    data = pickle.load(f)
    f.close
    D = data
else:
    f = open("factors.dat", 'wb')
==========

Doesn't work. What would?

> If you're curious about the protocol, you can disassemble a pickle
> using pickletools.dis(pickle), where pickle is bytes or a file-like
> object.

I'll give that a try.

Thanks!

Dick Moores


More information about the Tutor mailing list