Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Saving and loading multiple objects in pickle file?

I have a class that serves players in a game, creates them and other things.

I need to save these player objects in a file to use it later. I've tried the pickle module but I don't know how to save multiple objects and again loading them? Is there a way to do that or should I use other classes such as lists and save and load my objects in a list?

Is there a better way?

like image 306
hamidfzm Avatar asked Dec 21 '13 07:12

hamidfzm


People also ask

How do you store multiple items in pickles?

To save and load multiple objects in pickle file with Python, we can call pickle. load to load all the objects that are pickled in the file. to create the loadall function that opens the filename file with open .

Can you pickle multiple objects Python?

pickle will read them in the same order you dumped them in. Prints out ['One', 'Two', 'Three'] ['1', '2', '3'] . To pickle an arbitrary number of objects, or to just make them easier to work with, you can put them in a tuple, and then you only have to pickle the one object.

Can pickle save objects?

Pickling is a method to convert an object (list, dict, etc) to a file and vice versa. The idea is to save one or more objects in one script and load them in another. You can also use it to save program or game states.


1 Answers

Two additions to Tim Peters' accepted answer.

First, you need not store the number of items you pickled separately if you stop loading when you hit the end of the file:

def loadall(filename):     with open(filename, "rb") as f:         while True:             try:                 yield pickle.load(f)             except EOFError:                 break  items = loadall(myfilename) 

This assumes the file contains only pickles; if there's anything else in there, the generator will try to treat whatever else is in there as pickles too, which could be dangerous.

Second, this way, you do not get a list but rather a generator. This will load only one item into memory at a time, which is useful if the dumped data is very large -- one possible reason why you may have wanted to pickle multiple items separately in the first place. You can still iterate over items with a for loop as if it were a list.

like image 97
Lutz Prechelt Avatar answered Sep 21 '22 03:09

Lutz Prechelt