dcrearer dcrearer - 6 months ago 18
Python Question

Python3.4 pickle dump function fails with TypeError

I have a simple script that is suppose to import a module that initializes a db dictionary. The script then should open a file and use pickle.dump to write the db dictionary to the file. However it fails with the following TypeError:

Traceback (most recent call last):
File "make_db_pickle.py", line 6, in <module>
pickle.dump(db, dbfile)
TypeError: must be str, not bytes

from initdata import db
import pickle
dbfile = open('people_pickle', 'w')
pickle.dump(db, dbfile)
dbfile.close()


The type function show my variables dbfile and db as:

<class '_io.TextIOWrapper'>
<class 'dict'>

Answer

You need to open in binary mode i.e wb:

 open('people_pickle', 'wb')
Comments