Pickle ImportError:没有名为__builtin__的模块

时间:2017-09-21 18:07:28

标签: python module importerror

我正在尝试在python3.6中加载(复制的)pickle对象,当我这样做时,我得到__builtin__\r的导入错误。

with open('FilePath/FileName.pkl', "rb") as file:
    file = pickle.load(file)
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-36-b39fbab9bab4> in <module>()
      1 with open('FilePath/FileName.pkl', "rb") as file:
----> 2     file = pickle.load(file)

ModuleNotFoundError: No module named '__builtin__\r'

当我在python 2.7中尝试相同的操作时,我再次获得导入错误,__builtin__模块:

---------------------------------------------------------------------------

ImportError                               Traceback (most recent call last)
<ipython-input-3-12ac6524bf1a> in <module>()
      1 with open('FilePath/FileName.pkl', "rb") as file:
----> 2     file = pickle.load(file)

/Users/manasa.bulusu/anaconda2/lib/python2.7/pickle.pyc in load(file)
   1382 
   1383 def load(file):
-> 1384     return Unpickler(file).load()
   1385 
   1386 def loads(str):

/Users/manasa.bulusu/anaconda2/lib/python2.7/pickle.pyc in load(self)
    862             while 1:
    863                 key = read(1)
--> 864                 dispatch[key](self)
    865         except _Stop, stopinst:
    866             return stopinst.value

/Users/manasa.bulusu/anaconda2/lib/python2.7/pickle.pyc in load_global(self)
   1094         module = self.readline()[:-1]
   1095         name = self.readline()[:-1]
-> 1096         klass = self.find_class(module, name)
   1097         self.append(klass)
   1098     dispatch[GLOBAL] = load_global

/Users/manasa.bulusu/anaconda2/lib/python2.7/pickle.pyc in find_class(self, module, name)
   1128     def find_class(self, module, name):
   1129         # Subclasses may override this
-> 1130         __import__(module)
   1131         mod = sys.modules[module]
   1132         klass = getattr(mod, name)

ImportError: No module named __builtin__

我导入了builtins(py3.6)和__builtin__(py2.7),但这并没有停止抛出完全相同的错误。
这里的实际问题是什么?此外,__builtin__\r在py36中甚至看起来不像真正的包。

1 个答案:

答案 0 :(得分:2)

这看起来像你在Windows(以及Python 2)上以文本模式编写了pickle。使用文本模式是一个坏主意,因为\n - &gt; \r\n转换使得这些pickle在非Windows或Python 3上无法读取。

以二进制模式读取数据并在.replace(b'\r\n', b'\n')之前调用loads可能允许您加载数据,就像在Python 2上重新加载Windows上的数据并以二进制模式重新加载它一样。