Skip to main content
MahiDev — Learn. Build. Become AI-ready.

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().

Intermediate25 min
Pickling and unpickling hero Module 16 Lesson 8 dump and 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() and writelines() feel slow
  • pickle.dump(object, handle) for serialization
  • pickle.load(handle) for de-serialization
  • Why pickle files must be opened in binary mode

The idea

One object crosses in a single operation

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:

  1. import pickle
  2. Open the file in a binary write mode such as "wb"
  3. Build the object, often a list or a dict
  4. 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:

  1. import pickle
  2. Open the file in "rb"
  3. 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

python
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) and pickle.load(handle)

  • Always open pickle files with wb and rb

  • load() on a broken file can raise EOFError

  • Previous: Binary Files

  • Next: csv.writer and csv.reader

Loading playground…

Check your understanding

Pickling and unpickling quiz

Pickling is also called:

1 / 10