Fundamentals 4 min read

Understanding Python's pickle Module: Serialization and Deserialization

Python's pickle module provides a simple way to serialize and deserialize complex objects such as lists, dictionaries, and class instances, allowing them to be saved to or loaded from files or byte streams, with examples of pickling, unpickling, using dumps/loads, protocol versions, and security considerations.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Understanding Python's pickle Module: Serialization and Deserialization

The pickle module in Python enables object serialization (pickling) and deserialization (unpickling), allowing complex data structures like lists, dictionaries, and class instances to be persisted to files or transferred as byte streams.

Basic concepts : Serialization converts an object into a storable format, while deserialization reconstructs the original object from that format.

Serializing an object (Pickling) – the following code demonstrates how to pickle a dictionary containing a list and save it to a file:

import pickle

data = {'key': 'value', 'numbers': [1, 2, 3, 4]}
with open('data.pkl', 'wb') as f:
    pickle.dump(data, f, pickle.HIGHEST_PROTOCOL)
print("数据已保存")

In this example, the data structure is written to data.pkl using binary mode ( wb ).

Deserializing an object (Unpickling) – to load the previously saved object:

import pickle

with open('data.pkl', 'rb') as f:
    loaded_data = pickle.load(f)
print("加载的数据:", loaded_data)

The file is opened in binary read mode ( rb ) and pickle.load restores the original Python object.

Other functions : pickle.dumps() and pickle.loads() work with byte strings instead of files, useful for network transmission or in‑memory processing.

import pickle

data = {'key': 'value'}
dump_data = pickle.dumps(data)
print("序列化后的数据:", dump_data)
load_data = pickle.loads(dump_data)
print("反序列化后的数据:", load_data)

Protocol versions : pickle supports multiple protocol versions; by default it uses the highest available. You can specify a version (e.g., pickle.HIGHEST_PROTOCOL or an integer like 2 ).

Security note : pickle is not safe for untrusted data because pickle.loads() can execute arbitrary code. For cross‑platform or security‑critical scenarios, consider safer formats such as JSON.

Overall, pickle offers a convenient way to persist almost any Python object, simplifying data storage and transfer, but it should be used with caution regarding security.

PythonSerializationdeserializationData PersistencePickle
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.