LambdaLabTM
Computer Science · Class 12 · Binary Files
Binary filespickle⏱️ 12 min read

The pickle Module

One import and two methods. That is the whole tool set for the rest of this chapter — dump() to put an object into a file, load() to get it back. Everything after this lesson is those two in a loop.

1import pickle

pickle is a standard library module — it comes with Python, like math and random. Nothing to download or install. One line at the top of the program:

importing.py
import pickle

Forget it, and the first call fails with a familiar message:

forgot_import.py
f = open('marks.dat', 'wb')
pickle.dump([78, 91, 65], f)
Output
Traceback (most recent call last):
  File "forgot_import.py", line 2, in <module>
    pickle.dump([78, 91, 65], f)
NameError: name 'pickle' is not defined. Did you forget to import 'pickle'?

2dump() — the object goes in

pickle.dump(object, file)
first: what to save

Any Python object — a list, a dictionary, a number.

second: where to put it

The file handle — open in a binary writing mode.

dumping.py
import pickle

marks = [78, 91, 65]

f = open('marks.dat', 'wb')
pickle.dump(marks, f)
f.close()

print('saved')
Output
saved
The order catches everybody
The object first, the file second. Get them the wrong way round and Python says TypeError: file must have a 'write' attribute — it was handed a list where it expected a file.
Note
dump() gives back None, like write() gives back a count nobody uses. The worth of the call is the change it makes to the file, not an answer to catch.

3load() — the object comes back

object = pickle.load(file)

One argument — the file handle, open in a binary reading mode. What comes back is the object.

loading.py
import pickle

f = open('marks.dat', 'rb')
marks = pickle.load(f)
f.close()

print(marks)
print(type(marks))
print(marks[0] + marks[1])
Output
[78, 91, 65]
<class 'list'>
169
open('marks.dat', 'rb')

Reading, and binary. 'r' alone would raise UnicodeDecodeError before pickle got a look at it.

marks = pickle.load(f)

Unlike dump(), this one HANDS SOMETHING BACK, so it needs a variable on the left. Forgetting that is the most common slip on this page.

marks[0] + marks[1]

78 + 91. It is a real list of real numbers — no int() anywhere.

4The two, side by side

Let's Recap!
pickle.dump()pickle.load()
Directionobject → filefile → object
Argumentsthe object, then the filethe file
File mode needed'wb' or 'ab' (or a + mode)'rb' (or a + mode)
Gives backNonethe object that was saved
Calledonce per object savedonce per object read
The word for itpickling / serializationunpickling / deserialization

5The whole round trip

Six lines, and every binary-file program in the chapter is a version of them. Note the file is closed after writing and opened again for reading — the same handle cannot be used, because it was opened in a writing mode.

round_trip.py
Close before you read
What dump() writes sits in a buffer until the file is closed — exactly as the closing lesson showed. Try to read the file before close() has run and there may be nothing in it yet.

6Four mistakes worth knowing in advance

pickle.dump(f, marks)

Arguments swapped. TypeError: file must have a 'write' attribute.

pickle.load(f) with nothing on the left

The object is read and thrown away. The program runs, prints nothing, and looks broken for no visible reason.

open('marks.dat', 'w')

Text mode. TypeError: write() argument must be str, not bytes.

Reading before closing

The bytes may still be in the buffer. Close the file you wrote, then open it again to read.

7Recap

import pickle

A standard library module. Nothing to install, one line at the top.

pickle.dump(object, file)

Writes the object into the file as bytes. Object first, file second. Returns None.

object = pickle.load(file)

Reads one object back and hands it over — with its original type.

The mode must be binary

'wb' or 'ab' to dump, 'rb' to load. Forgetting the b is the usual first error.

Close before reading back

What was dumped may still be in the buffer until close() runs.

One dump, one load

Each call handles one object. Several records mean several calls — which is the next lesson.

✍️ Now write these yourself
  1. 1

    Pickle a tuple into a file and load it back. Check its type().

    Hint · tuple, not list. Pickle gives back exactly what went in.

  2. 2

    Swap the two arguments of dump() on purpose and read the error.

    Hint · file must have a 'write' attribute.

  3. 3

    Write pickle.load(f) without putting the answer in a variable, then print it.

    Hint · You cannot — it is gone. That is why the variable matters.

  4. 4

    Save a dictionary of your own marks, then load it and print one subject.

    Hint · back['maths'] — a real dictionary, so real keys.

Quick Check

Which is the correct call to save the list marks into the open file f?

Quick Check

What does pickle.load(f) give back?

Quick Check

Which mode must the file be open in for pickle.load()?

Quick Check

Is pickle a module you have to install?