coledavis (2) [Avatar] Offline
pp 167-168. On two occasions, the reader is told that the variables to be stored can include anything, including numbers. Well numbers as variables are exactly what I'd like to store, but this is what happened (using simple example from these pages). Python command line used:

import pickle # No problem
a = 23
b = 33
c = 43
file = open("state", 'w') # Still no problem
pickle.dump(a, file) # ALARM

Message: Traceback (most recent call last):
File "<stdin>", line 1 in <module>
File "", line 1354, in dump
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
Typeerror: must be str, not bytes
naomi.ceder (134) [Avatar] Offline
Re: pickling

Ouch... I'm still trying to figure out how this one slipped by me...

In any case, the problem is that the file is not being opened in binary mode, so it's giving you a string, while the pickle routines are expected bytes.

To make this work, change the way you open files from 'w' to 'wb' and (when loading) from 'r' to 'rb':

file = open("state", 'w')

should be

file = open("state", 'wb')


file = open("state", 'r')

should be

file = open("state", 'rb')

Thanks for pointing this mistake out - it got by all of us.


Message was edited by: Vern Ceder