What is Pickling and Unpickling?
What is Pickling and Unpickling?
Pickling and unpickling are terms used in Python to describe the process of serializing and deserializing objects, respectively. These processes are crucial for saving Python objects to a file or transmitting them over a network by converting them into a byte stream and then reconstructing them back into Python objects.
Pickling, also known as serialization, involves converting a Python object hierarchy into a byte stream. This is typically done to save the state of an object so that it can be persisted to disk or sent over a network. The pickle
module in Python provides this functionality through the dump()
and dumps()
functions. The dump()
function serializes an object directly to a file-like object, while dumps()
returns the serialized object as a byte string[1][2][3].
Here is a simple example of pickling:
import pickle
# Define a Python object
person = {"name": "Alice", "age": 30, "gender": "female"}
# Pickle the object to a binary file
with open("person.pickle", "wb") as file:
pickle.dump(person, file)
Unpickling is the inverse process of pickling. It involves converting a byte stream back into a Python object hierarchy. This is useful for reconstructing Python objects from files or network streams where the byte stream was previously generated by pickling. The pickle
module provides the load()
and loads()
functions for this purpose. The load()
function deserializes from a file-like object, while loads()
deserializes from a byte string[1][2][...
middle
Gợi ý câu hỏi phỏng vấn
Chưa có bình luận nào