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

1

8

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".

Hindermost answered 29/1, 2018 at 10:19 Comment(2)
All of the information you seek is readily accessible from the documentation.Erratic
I'm voting to close this question as off-topic because it is trivially available from the documentation.Padding
E
22

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.

Erratic answered 29/1, 2018 at 10:22 Comment(1)
So this has nothing to do with how we dump the object? I mean, we don't have to use .load() only on an object that is .dump() and we can use .load() on an object that is .dumps() too? There is no one-on-one mapping on using .dump()/.load() and .dumps()/.loads() and what only matters is the type of the file to load, byte string or file-like. Am I right?Storytelling

© 2022 - 2024 — McMap. All rights reserved.