Pickle UnicodeDecodeError

时间:2017-02-15 17:40:25

标签: python python-3.x object pickle

我想在文件中存储一个包含多个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

有没有人知道如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

问题是您编写了文件二进制模式('wb'),但后来尝试以文本模式('r')重新读取它。所以要解决这个问题,你需要做的就是换一行:

@staticmethod
    def loadMemory(filename):
        filehandler = open(filename, 'rb')  # must read in binary mode, too
        memory = pickle.load(filehandler)
        return memory