Reputation: 153
When I use pickle module,I can use pickle.dump()
method to save many objects in file. But when I use Pickle.load()
,this method only can load one object.What I should do when I want to load all objects?
Upvotes: 1
Views: 7011
Reputation: 155046
Your answer indicates that you are using multiple invocations of dump
to dump multiple objects into the same stream. If that is the case, it is expected that you know how many times to call load
, e.g. by obtaining the information from the first loaded object, or by the number of objects being constant.
If that is not the case, use a single dump
to dump all the objects by packing them up in a tuple:
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
:
objs = []
while True:
try:
o = pickle.load(f)
except EOFError:
break
objs.append(o)
Upvotes: 5