我想在一个文件中存储一个包含多个 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
有人知道如何解决这个问题吗?
最佳答案
问题是您以二进制模式 ('wb'
) 编写了文件,但随后尝试以文本模式 ('r'
) 将其读回。因此,要修复它,您需要做的就是更改一行:
@staticmethod
def loadMemory(filename):
filehandler = open(filename, 'rb') # must read in binary mode, too
memory = pickle.load(filehandler)
return memory
关于python - pickle UnicodeDecodeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42256479/