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

我是研究僧i 提交于 2019-12-23 07:01:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!