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!