使用pickle.dump - TypeError:必须是str,而不是bytes

Joh*_*and 210 python pickle python-3.x

我正在使用python3.3并且在尝试挑选一个简单的字典时遇到了一个神秘的错误.

这是代码:

import os
import pickle
from pickle import *
os.chdir('c:/Python26/progfiles/')

def storvars(vdict):      
    f = open('varstor.txt','w')
    pickle.dump(vdict,f,)
    f.close()
    return

mydict = {'name':'john','gender':'male','age':'45'}
storvars(mydict)
Run Code Online (Sandbox Code Playgroud)

我得到:

Traceback (most recent call last):
  File "C:/Python26/test18.py", line 31, in <module>
    storvars(mydict)
  File "C:/Python26/test18.py", line 14, in storvars
    pickle.dump(vdict,f,)
TypeError: must be str, not bytes
Run Code Online (Sandbox Code Playgroud)

Jon*_*nts 357

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

f = open('varstor.txt','w')
Run Code Online (Sandbox Code Playgroud)

需要是:

f = open('varstor.txt','wb')
Run Code Online (Sandbox Code Playgroud)

  • *遇到完全相同的问题之后,我在[docs](https://docs.python.org/3/library/pickle.html#pickle)中看到了"二进制"阅读/写作的需求. dump)用于`pickle.dump()`和`pickle.load()`.两个地方,这只是在功能解释的中间附近提到.有人应该让这个更清楚. (19认同)
  • 我用Python项目提交了[#24159](http://bugs.python.org/issue24159).也许可以采取一些措施来改善这种情况和类似情况. (8认同)

Wel*_*ith 14

刚遇到同样的问题.在Python 3中,必须指定二进制模式'wb','rb',而在Python 2x中,不需要它们.当您按照基于Python 2x的教程进行操作时,这就是您来到这里的原因.

import pickle

class MyUser(object):
    def __init__(self,name):
        self.name = name

user = MyUser('Peter')

print("Before serialization: ")
print(user.name)
print("------------")
serialized = pickle.dumps(user)
filename = 'serialized.native'

with open(filename,'wb') as file_object:
    file_object.write(serialized)

with open(filename,'rb') as file_object:
    raw_data = file_object.read()

deserialized = pickle.loads(raw_data)


print("Loading from serialized file: ")
user2 = deserialized
print(user2.name)
print("------------")
Run Code Online (Sandbox Code Playgroud)