[Tutor] pickle problems

eryksun eryksun at gmail.com
Sun Aug 12 05:50:33 CEST 2012


On Sat, Aug 11, 2012 at 10:43 PM, Richard D. Moores <rdmoores at gmail.com> wrote:
>
> 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')

The extension doesn't affect anything about the file. It's just .txt
indicates a text file.

> 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?

Opening in mode 'wb' truncates the file. Then pickle.dump() writes the
pickle to it. Before you were appending to the end of the file, so you
had multiple pickled dictionaries stored in the file.

> 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')

You can catch the IOError if the file doesn't exist or
pickle.PickleError if it's corrupted, and just assign an empty dict.

try:
    with open("factors.dat", 'rb') as f:
        D = pickle.load(f)
except (IOError, pickle.PickleError):
    D = {}

There's no reason to open the file for writing at this point. You do that later.


More information about the Tutor mailing list