Pickle
pickle is a Python module used to serialize and deserialize Python objects. It can be used to store and retrieve Python objects from disk.
Serialization
Serialization is the process of converting a Python object into a byte stream. This byte stream can be stored on disk or sent over a network.
The pickle.dump()
function is used to serialize a Python object. It takes two arguments: the object to serialize and a file object to write the byte stream to.
import pickle
= {'name': 'Alice', 'age': 25}
data
with open('data.pickle', 'wb') as f:
pickle.dump(data, f)
In this example, we serialize a dictionary containing a person’s name and age to a file called data.pickle
.
Deserialization
Deserialization is the process of converting a byte stream back into a Python object.
The pickle.load()
function is used to deserialize a Python object. It takes a file object containing the byte stream as an argument and returns the deserialized object.
with open('data.pickle', 'rb') as f:
= pickle.load(f)
data
print(data)
In this example, we deserialize the byte stream from the data.pickle
file back into a Python object and print it.
Security
It is important to note that the pickle
module is not secure. Deserializing untrusted data can lead to security vulnerabilities, as malicious code can be executed during deserialization. It is recommended to only deserialize data from trusted sources.