Python Pickle:TypeError:需要一个类似字节的对象,而不是“str”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39146039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Pickle: TypeError: a bytes-like object is required, not 'str'
提问by D Xia
I keep on getting this error when I run the following code in python 3:
当我在 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?
我尝试通过 encode 函数将 fname1 转换为字节,但仍然没有解决问题。有人可以告诉我出了什么问题吗?
回答by Farhan.K
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:
顺便说一句,您应该使用with
来处理打开/关闭文件:
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)
回答by MonRaj
In Python 3 you need to specifically call either 'rb' or 'wb'.
在 Python 3 中,您需要专门调用“rb”或“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)
回答by Jun
You need to change 'str' to 'bytes'. Try this:
您需要将“str”更改为“bytes”。尝试这个:
class StrToBytes:
def __init__(self, fileobj):
self.fileobj = fileobj
def read(self, size):
return self.fileobj.read(size).encode()
def readline(self, size=-1):
return self.fileobj.readline(size).encode()
with open(fname, 'r') as f:
obj = pickle.load(StrToBytes(f))
回答by Dopple
I keep coming back to this stack overflow link, so I'm posting the real answer for the next time I come looking for it:
我一直回到这个堆栈溢出链接,所以我将在下次寻找它时发布真正的答案:
PickleDB is messed up and needs to be fixed.
PickleDB 搞砸了,需要修复。
Line 201 of pickledb.py
pickledb.py 的第 201 行
From:
从:
simplejson.dump(self.db, open(self.loco, 'wb'))
to:
到:
simplejson.dump(self.db, open(self.loco, 'wt'))
Problem solved forever.
问题永远解决了。