问题
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".
回答1:
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.
来源:https://stackoverflow.com/questions/48498929/what-is-file-like-object-what-is-file-pickle-load-and-pickle-loads