Python 泡菜独角兽
我想在一个文件中存储一个包含多个Python 泡菜独角兽,python,python-3.x,object,pickle,Python,Python 3.x,Object,Pickle,我想在一个文件中存储一个包含多个numpy数组的Python对象。我发现了pickle,但在加载存储对象时,我总是得到一个UnicodeDecodeError: 回溯(最近一次呼叫最后一次): 文件“system.py”,第46行,在 m2=System.loadMemory('m1.pickle') loadMemory中第28行的文件“system.py” 内存=pickle.load(filehandler) 文件“/home/daniel-u1/anaconda3/lib/python3
numpy
数组的Python对象。我发现了pickle
,但在加载存储对象时,我总是得到一个UnicodeDecodeError
:
回溯(最近一次呼叫最后一次):
文件“system.py”,第46行,在
m2=System.loadMemory('m1.pickle')
loadMemory中第28行的文件“system.py”
内存=pickle.load(filehandler)
文件“/home/daniel-u1/anaconda3/lib/python3.5/codecs.py”,第321行,在
解码(结果,消耗)=自。\缓冲区\解码(数据,自错误,最终)
UnicodeDecodeError:“utf-8”编解码器无法解码位置0中的字节0x80:无效的开始字节
方法saveMemory
工作正常,但loadMemory
在pickle.load
处抛出错误:
@staticmethod
def saveMemory(m1, filename):
filehandler = open(filename, 'wb')
pickle.dump(m1, filehandler)
@staticmethod
def loadMemory(filename):
filehandler = open(filename, 'r')
memory = pickle.load(filehandler)
return memory
有人知道如何解决这个问题吗?问题是您以二进制模式(
'wb'
)编写了文件,但随后尝试以文本模式('r'
)将其读回。因此,要解决此问题,您只需更改一行:
@staticmethod
def loadMemory(filename):
filehandler = open(filename, 'rb') # must read in binary mode, too
memory = pickle.load(filehandler)
return memory
为什么要以二进制模式写入文件,而以文本模式读取?换句话说,使用
open(filename,'rb')
在loadMemory()
@martineau()中打开文件。非常感谢,这就是问题所在。请你在另一个帖子中回答,这样我就可以把这个问题标记为已解决了?