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.
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:
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:
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:
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 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:
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.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
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!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
