what is "file_like_object", what is "file"; pickle.load() and pickle.loads()

Eric Kani picture Eric Kani · Jan 29, 2018 · Viewed 9k times · Source

I am figuring out the differences between the pickle.load() and pickle.loads(). Somebody said what kind of object that pickle.load() process is "file_like_object", however, pickle.loads() corresponds to "file object".

Answer

Jonathon Reinhart picture Jonathon Reinhart · Jan 29, 2018

Your choice of which function to use depends on the object from whence you are loading the pickled data:


pickle.loads is used to load pickled data from a bytes string. The "s" in loads refers to the fact that in Python 2, the data was loaded from a string.

For example:

import pickle

with open("myobj.pickle", "rb") as f:
    rawdata = f.read()

myobj = pickle.loads(rawdata)

pickle.load is used to load pickled data from a file-like object. This is any object that acts like a file - in this case, meaning it has a read() method that returns bytes.

For example:

import pickle

with open("myobj.pickle", "rb") as f:
    myobj = pickle.load(f)

This same convention applies to the dump/dumps functions in the pickle library, as well as the json module and others.