Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 240
D Xia Avatar asked Aug 25 '16 12:08

D Xia


2 Answers

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) 
like image 162
Farhan.K Avatar answered Sep 23 '22 04:09

Farhan.K


In Python 3 you need to specifically call either 'rb' or 'wb'.

with open('C:\Users\Dorien Xia\Desktop\Pokemon-Go-Bot-Working-Hack-API-master\pgoapi\pgoapi.py', 'rb') as file:     data = pickle.load(file) 
like image 43
MonRaj Avatar answered Sep 23 '22 04:09

MonRaj