Home >Backend Development >Python Tutorial >How to Serialize and Deserialize Multiple Objects with Pickle in Python?

How to Serialize and Deserialize Multiple Objects with Pickle in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-03 19:10:29236browse

How to Serialize and Deserialize Multiple Objects with Pickle in Python?

Multiple Object Serialization and Deserialization with Pickle

In Python, the pickle module provides a convenient way to serialize and deserialize objects, but how do you handle multiple objects?

To save multiple objects in a pickle file, you can use a list or tuple to aggregate them. For instance:

<code class="python">my_objects = [obj1, obj2, obj3]
with open('objects.pkl', 'wb') as f:
    pickle.dump(my_objects, f)</code>

To load the objects, simply:

<code class="python">with open('objects.pkl', 'rb') as f:
    my_objects = pickle.load(f)</code>

The pickle module supports storing the number of items being pickled, making it possible to load them individually. However, for larger datasets, loading everything into memory may not be optimal.

An alternative is to use a generator to load the objects one at a time:

<code class="python">def loadall(filename):
    with open(filename, "rb") as f:
        try:
            while True:
                yield pickle.load(f)
        except EOFError:
            pass</code>

This way, only the next object is loaded when needed, conserving memory.

The above is the detailed content of How to Serialize and Deserialize Multiple Objects with Pickle in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn