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:
import pickleForget it, and the first call fails with a familiar message:
f = open('marks.dat', 'wb')
pickle.dump([78, 91, 65], f)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)Any Python object — a list, a dictionary, a number.
The file handle — open in a binary writing mode.
import pickle
marks = [78, 91, 65]
f = open('marks.dat', 'wb')
pickle.dump(marks, f)
f.close()
print('saved')saved
TypeError: file must have a 'write' attribute — it was handed a list where it expected a file.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.
import pickle
f = open('marks.dat', 'rb')
marks = pickle.load(f)
f.close()
print(marks)
print(type(marks))
print(marks[0] + marks[1])[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
| pickle.dump() | pickle.load() | |
|---|---|---|
| Direction | object → file | file → object |
| Arguments | the object, then the file | the file |
| File mode needed | 'wb' or 'ab' (or a + mode) | 'rb' (or a + mode) |
| Gives back | None | the object that was saved |
| Called | once per object saved | once per object read |
| The word for it | pickling / serialization | unpickling / 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.
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 leftThe 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 closingThe bytes may still be in the buffer. Close the file you wrote, then open it again to read.
7Recap
A standard library module. Nothing to install, one line at the top.
Writes the object into the file as bytes. Object first, file second. Returns None.
Reads one object back and hands it over — with its original type.
'wb' or 'ab' to dump, 'rb' to load. Forgetting the b is the usual first error.
What was dumped may still be in the buffer until close() runs.
Each call handles one object. Several records mean several calls — which is the next lesson.
- 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
Swap the two arguments of dump() on purpose and read the error.
Hint · file must have a 'write' attribute.
- 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
Save a dictionary of your own marks, then load it and print one subject.
Hint · back['maths'] — a real dictionary, so real keys.
Which is the correct call to save the list marks into the open file f?
What does pickle.load(f) give back?
Which mode must the file be open in for pickle.load()?
Is pickle a module you have to install?