Usage of pickle.dump in Python

Sergey picture Sergey · Jan 2, 2012 · Viewed 30.9k times · Source

I'm trying to learn how to use the pickle module in Python:

import pickle
x = 123
f = open('data.txt','w')
pickle.dump(x,f)

Here's what I get:

Traceback (most recent call last):
  File "D:\python\test.py", line 5, in <module>
    pickle.dump(x,f)
TypeError: must be str, not bytes

However, this code works just fine:

import pickle
dump = pickle.dump(123)
print(dump)


What am I doing wrong?

Answer

DSM picture DSM · Jan 2, 2012

The problem is that you're opening the file in text mode. You need to use binary here:

>>> f = open('data.txt','w')
>>> pickle.dump(123,f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not bytes
>>> 
>>> f = open('data.txt','wb')
>>> pickle.dump(123,f)
>>>