Fundamentals 6 min read

Master Python’s Pickle: Serialize Objects Easily with Real Code Examples

This article introduces Python’s pickle module, explains its purpose for object persistence, details key functions like dump, dumps, load, and loads with code snippets and example outputs, and demonstrates practical usage scenarios and common pitfalls, helping readers efficiently serialize and deserialize data in Python.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python’s Pickle: Serialize Objects Easily with Real Code Examples

What is the pickle module?

Pickle is a Python-specific persistence module that can serialize various data, including custom classes, making it suitable for storing complex Python objects.

However, the serialized string is not human‑readable and can only be used within Python environments, so it is not suitable for data exchange with other languages.

Purpose of the pickle module

It allows you to save Python objects directly to a file without converting them to strings first, handling the binary format automatically and reducing the amount of code needed for file I/O.

Main methods

1. pickle.dump(obj, file)

Saves a Python object to a file in pickle format.

with open('data.pickle', 'wb') as f:
    pickle.dump(data, f)

Opening the resulting file in a text editor shows unreadable binary data.

Result:

pickle dump output
pickle dump output

2. pickle.dumps(obj)

Serializes a Python object to a bytes string.

import pickle
dic = {"k1":"v1","k2":123}
s = pickle.dumps(dic)
print(s)

Result:

pickle.dumps output
pickle.dumps output

3. pickle.load(file)

Loads data from a pickle file and converts it back to Python objects.

with open('data.pickle', 'rb') as f:
    data = pickle.load(f)

4. pickle.loads(bytes_object)

Deserializes a bytes string produced by pickle.dumps back into Python objects.

import pickle
dic = {"k1":"v1","k2":123}
s = pickle.dumps(dic)
dic2 = pickle.loads(s)
print(dic2)

Result:

pickle.loads output
pickle.loads output

Project demonstration

Example 1

import pickle

with open('data.pickle', 'rb') as f:
    data = pickle.load(f)

The .pickle file appears as garbled text when opened with a plain text editor.

Result:

example 1 output
example 1 output

Example 2

Pickle can serialize custom Python classes, but the class definition must be available when deserializing.

import pickle

class Person:
    def __init__(self, n, a):
        self.name = n
        self.age = a

    def show(self):
        print(self.name + "_" + str(self.age))

aa = Person("张三", 20)
aa.show()
f = open('2.txt', 'wb')
pickle.dump(aa, f)
f.close()
# del Person  # If this line were uncommented, loading would fail
f = open('2.txt', 'rb')
bb = pickle.load(f)
f.close()
bb.show()

Result:

example 2 output
example 2 output

Conclusion

This article introduced Python’s pickle module, detailed its main functions, addressed common issues, and provided practical code examples to help readers understand and apply pickle for object persistence in real projects.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

serializationfile I/OData PersistencePickle
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

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.