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

Mary-Kate Olsen
Release: 2024-11-03 19:10:29
Original
168 people have browsed it

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>
Copy after login

To load the objects, simply:

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!