[Tutor] Cannot cPickle.load()

Brian van den Broek bvande at po-box.mcgill.ca
Wed Dec 1 20:05:57 CET 2004

Tim Peters said unto the world upon 2004-11-30 20:54:

> Change
>     "r"
> to
>     "rb"
> and try again.
> You're on Windows, pickles are binary files, and binary files must
> always be opened in binary mode on Windows.  When you wrote the data
> to the file to begin with, I hope you opened the file in binary mode
> then too.  Else the data in the file is corrupt now.

Hi all,

Tim's post confuses me. (I've cc'ed you Tim as somehow I doubt you are a 
regular reader of Tutor -- apologies if that annoys.)

I'm on Windows with Python 2.3.4 (waiting for extension updates to use 
2.4). When I run:

import pickle

a_dict = {1:2, 3:4, 5:6}
print a_dict

pic_file = file('c:/testpickle.pic', 'w')
pickle.dump(a_dict, pic_file)

a_dict = {}
print a_dict

pic_file = file('c:/testpickle.pic', 'r')
a_dict = pickle.load(pic_file)
print a_dict

I get the output:

IDLE 1.0.3
 >>> ========================= RESTART =======================
{1: 2, 3: 4, 5: 6}
{1: 2, 3: 4, 5: 6}

Which makes it look to me like pickle is working just fine without using 
binary mode. I tried the same thing with cPickle and also made sure to 
close IDLE and try reading the pickled data in a command prompt Python.

In all cases, I recovered the pickled data without difficulty.

So, what have I misunderstood?

Thanks, and best to all,

Brian vdB

More information about the Tutor mailing list