我想在文件中存储一个包含多个numpy
数组的Python对象。我找到pickle
但是在加载存储对象时我总是得到UnicodeDecodeError
:
Traceback (most recent call last):
File "system.py", line 46, in <module>
m2 = System.loadMemory('m1.pickle')
File "system.py", line 28, in loadMemory
memory = pickle.load(filehandler)
File "/home/daniel-u1/anaconda3/lib/python3.5/codecs.py", line 321, in
decode (result, consumed) = self._buffer_decode(data, self.errors, final)
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte
方法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
有没有人知道如何解决这个问题?
答案 0 :(得分:2)
问题是您编写了文件二进制模式('wb'
),但后来尝试以文本模式('r'
)重新读取它。所以要解决这个问题,你需要做的就是换一行:
@staticmethod
def loadMemory(filename):
filehandler = open(filename, 'rb') # must read in binary mode, too
memory = pickle.load(filehandler)
return memory