Pickle: TypeError: a bytes-like object is required, not 'str'

D Xia picture D Xia · Aug 25, 2016 · Viewed 44.4k times · Source

I keep on getting this error when I run the following code in python 3:

fname1 = "auth_cache_%s" % username
fname=fname1.encode(encoding='utf_8')
#fname=fname1.encode()
if os.path.isfile(fname,) and cached:
    response = pickle.load(open(fname))
else:
    response = self.heartbeat()
    f = open(fname,"w")
    pickle.dump(response, f)

Here is the error I get:

File "C:\Users\Dorien Xia\Desktop\Pokemon-Go-Bot-Working-Hack-API-master\pgoapi\pgoapi.py", line 345, in login
    response = pickle.load(open(fname))
TypeError: a bytes-like object is required, not 'str'

I tried converting the fname1 to bytes via the encode function, but It still isn't fixing the problem. Can someone tell me what's wrong?

Answer

Farhan.K picture Farhan.K · Aug 25, 2016

You need to open the file in binary mode:

file = open(fname, 'rb')
response = pickle.load(file)
file.close()

And when writing:

file = open(fname, 'wb')
pickle.dump(response, file)
file.close()

As an aside, you should use with to handle opening/closing files:

When reading:

with open(fname, 'rb') as file:
    response = pickle.load(file)

And when writing:

with open(fname, 'wb') as file:
    pickle.dump(response, file)