The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

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 (135) [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