4

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'>
dcrearer
  • 1,972
  • 4
  • 24
  • 48
  • Related: https://stackoverflow.com/questions/13906623/using-pickle-dump-typeerror-must-be-str-not-bytes – 0 _ Sep 02 '17 at 21:11

1 Answers1

6

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

 open('people_pickle', 'wb')
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321
  • the solution provided works. Can you explain what the TraceBack is reporting: TypeError: must be str, not bytes. I don't understand what must be a str. – dcrearer May 14 '16 at 02:33
  • 1
    @dcrearer, when you open a file using just "w" then the file object is expecting a str i.e `open("foo.bin","w").write("foo")` works fine but `open("foo.bin","w").write("foo".encode("utf-8"))` will give you `TypeError: must be str, not bytes` as we have encoded the str to bytes which is what pickle also does, that is why you need to open in binary mode, `open("foo.bin","wb").write("foo".encode("utf-8"))` would work fine . – Padraic Cunningham May 14 '16 at 09:00