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?
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 .
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With