Categories
Python Answers

How to save and load multiple objects in pickle file with Python?

Spread the love

Sometimes, we want to save and load multiple objects in pickle file with Python.

In this article, we’ll look at how to save and load multiple objects in pickle file with Python.

How to save and load multiple objects in pickle file with Python?

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.

For instance, we write

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

items = loadall(my_filename)

to create the loadall function that opens the filename file with open.

In the with block, we create a while loop that yields the object returned by picke.load until a EOFError is raised.

Once the error is raised, we read all the items in the pickled file.

Conclusion

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *