Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用pickle.dump-TypeError:必须是str,而不是bytes_Python_Python 3.x_Pickle - Fatal编程技术网

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

Python 使用pickle.dump-TypeError:必须是str,而不是bytes,python,python-3.x,pickle,Python,Python 3.x,Pickle,我使用的是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 = {'

我使用的是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)
我得到:

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
回溯(最近一次呼叫最后一次):
文件“C:/Python26/test18.py”,第31行,在
storvars(mydict)
storvars中第14行的文件“C:/Python26/test18.py”
pickle.dump(vdict,f)
TypeError:必须是str,而不是bytes

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

f = open('varstor.txt','w')
需要:

f = open('varstor.txt','wb')

只是有同样的问题。在Python3中,必须指定二进制模式“wb”、“rb”,而在Python2X中,则不需要它们。当您学习基于Python2X的教程时,这就是您来到这里的原因

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("------------")

在遇到完全相同的问题后,我看到在for
pickle.dump()
pickle.load()
中提到了“二进制”读/写的需要。在这两个地方,这只是在函数解释的中间部分提到的。有人应该把这一点说清楚。我提交了Python项目。也许可以做些什么来改善这种情况和类似情况下的体验。FWIW,上面@Matthew评论中的docs链接没有提到“函数解释的中间部分”中需要二进制文件。也许他们从那时起就改变了?话虽如此,事后来看,我们可以搜索关键字“binary”,然后它会出现在文章最顶端的第一段/句子中。