简体   繁体   English

如何在python中加载pickle的所有对象?

[英]How to load all objects of pickle in python?

When I use pickle module,I can use pickle.dump() method to save many objects in file.当我使用 pickle 模块时,我可以使用pickle.dump()方法将许多对象保存在文件中。 But when I use Pickle.load() ,this method only can load one object.What I should do when I want to load all objects?但是当我使用Pickle.load()时,这个方法只能加载一个对象。当我想加载所有对象时应该怎么做?

Your answer indicates that you are using multiple invocations of dump to dump multiple objects into the same stream.您的回答表明您正在使用 dump 的多次调用将多个对象dump到同一流中。 If that is the case, it is expected that you know how many times to call load , eg by obtaining the information from the first loaded object, or by the number of objects being constant.如果是这种情况,您应该知道调用load的次数,例如,通过从第一个加载的对象获取信息,或者通过对象的数量保持不变。

If that is not the case, use a single dump to dump all the objects by packing them up in a tuple:如果不是这种情况,请使用单个dump通过将所有对象打包在一个元组中来转储所有对象:

pickle.dump((a, b, c), f)

You then will be able to load them in one go:然后您将能够一次性加载它们:

a, b, c = pickle.load(f)

If you cannot change the dumping code to use a tuple, you can simply load the data from the stream until encountering an EOFError :如果您不能更改转储代码以使用元组,您可以简单地从流中加载数据,直到遇到EOFError

objs = []
while True:
    try:
        o = pickle.load(f)
    except EOFError:
        break
    objs.append(o)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM