dcrearer dcrearer - 2 years ago 156
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)

The type function show my variables dbfile and db as:

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

Answer Source

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

 open('people_pickle', 'wb')
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download