Lesson 08
Pickling and Unpickling — pickle.dump() and pickle.load()
Pickle one whole Python object into a binary file with dump(), then restore that same object in a single read with load().
write() stores strings one chunk at a time. Pickling stores an entire object in one write. Unpickling reads that object back in one read.
Use the playground at the bottom of this page, then take the quiz.
What you will learn
- Why pickling exists when
write()andwritelines()feel slow pickle.dump(object, handle)for serializationpickle.load(handle)for de-serialization- Why pickle files must be opened in binary mode
The idea
Suppose a record has several fields: a label, a role, and a count. Saving it with write() means converting every field and calling write() several times. Pickling does that transfer in one write.
Pickling (object serialization) saves the whole object from memory into a file with a single write. It is a write operation.
Steps:
import pickle- Open the file in a binary write mode such as
"wb" - Build the object, often a list or a dict
pickle.dump(record, handle)
Unpickling (object de-serialization) reads the whole record back into memory with a single read. It is a read operation.
Steps:
import pickle- Open the file in
"rb" record = pickle.load(handle)
Pickle data is binary. Text modes "w" and "r" are the wrong choice and can raise an error or damage the record. An empty or cut-off pickle file can raise EOFError from load(). A missing file still raises FileNotFoundError at open().
The object in this lesson is a short roster entry with a general name. It is not copied from a private data file.
Example
import pickle
record = ["Avery Lane", "Guide", 3]
with open("record.bin", "wb") as handle:
pickle.dump(record, handle)
with open("record.bin", "rb") as handle:
restored = pickle.load(handle)
print(restored)
print(restored[0], restored[1])restored is a list again, with the same three fields. The playground prints the type as well. Change the label and run again. "wb" replaces the previous pickle.
Key takeaways
-
Pickling writes a whole object in one call
-
Unpickling reads that object back in one call
-
Use
pickle.dump(object, handle)andpickle.load(handle) -
Always open pickle files with
wbandrb -
load()on a broken file can raiseEOFError -
Previous: Binary Files
Loading playground…
Check your understanding
Pickling and unpickling quiz
Pickling is also called:
1 / 10