Search code examples
pythonclassobjectpython-3.xpickle

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?


Solution

  • Using a list, tuple, or dict is by far the most common way to do this:

    import pickle
    PIK = "pickle.dat"
    
    data = ["A", "b", "C", "d"]
    with open(PIK, "wb") as f:
        pickle.dump(data, f)
    with open(PIK, "rb") as f:
        print pickle.load(f)
    

    That prints:

    ['A', 'b', 'C', 'd']
    

    However, a pickle file can contain any number of pickles. Here's code producing the same output. But note that it's harder to write and to understand:

    with open(PIK, "wb") as f:
        pickle.dump(len(data), f)
        for value in data:
            pickle.dump(value, f)
    data2 = []
    with open(PIK, "rb") as f:
        for _ in range(pickle.load(f)):
            data2.append(pickle.load(f))
    print data2
    

    If you do this, you're responsible for knowing how many pickles are in the file you write out. The code above does that by pickling the number of list objects first.