Pickle:TypeError:需要类似字节的对象,而不是'str'

D X*_*Xia 25 python bots python-3.x

当我在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)
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误:

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'
Run Code Online (Sandbox Code Playgroud)

我尝试通过编码功能将fname1转换为字节,但它仍然没有解决问题.有人能告诉我什么是错的吗?

Far*_*n.K 37

您需要以二进制模式打开文件:

file = open(fname, 'rb')
response = pickle.load(file)
file.close()
Run Code Online (Sandbox Code Playgroud)

写作时:

file = open(fname, 'wb')
pickle.dump(response, file)
file.close()
Run Code Online (Sandbox Code Playgroud)

另外,您应该使用with处理打开/关闭文件:

阅读时:

with open(fname, 'rb') as file:
    response = pickle.load(file)
Run Code Online (Sandbox Code Playgroud)

写作时:

with open(fname, 'wb') as file:
    pickle.dump(response, file)
Run Code Online (Sandbox Code Playgroud)


小智 10

在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)
Run Code Online (Sandbox Code Playgroud)


小智 5

您需要将“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))
Run Code Online (Sandbox Code Playgroud)