Minu
Minu

Reputation: 480

Pickle ImportError: No module named __builtin__

I'm trying to load a (copied) pickle object in python3.6 and I get an Import Error for __builtin__\r when I do so.

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'

When I try the same in python 2.7, I get an Import Error again, for __builtin__ module:

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

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__

I imported builtins (py3.6) and __builtin__ (py2.7), but that didn't stop from throwing the exact same errors.
What is the actual problem here? Also, __builtin__\r doesn't even seem like a real package in py36.

Upvotes: 5

Views: 5695

Answers (1)

user2357112
user2357112

Reputation: 280182

This looks like you wrote the pickle in text mode on Windows (and on Python 2). Using text mode is a bad idea, because the \n->\r\n conversion makes such pickles unreadable on non-Windows, or on Python 3.

Reading the data in binary mode and calling .replace(b'\r\n', b'\n') before loadsing it would probably allow you to load the data, as would reloading the data on Windows on Python 2 and repickling it in binary mode.

Upvotes: 2

Related Questions