You are on page 1of 3

Python Programming home

Department of Computing, Imperial College London

Python for C++ Programmers


Chapter 1: Introduction
Chapter 2: Basic data types
Chapter 3: Variables and operators
Chapter 4: Sequence types
Chapter 5: Sets and dictionaries
Chapter 6: Control flow
Chapter 7: Functions
Chapter 8: Object-oriented programming
Chapter 9: Modules
Chapter 10: Files
[10.1] Handling text files
[10.2] JSON files
[10.3] Loading JSON files
[10.4] Writing to JSON files
[10.5] pickle
[10.6] Pickling time!
[10.7] CSV files
[10.8] Reading CSV files
[10.9] Reading CSV files into a dict
[10.10] Writing to CSV files
[10.11] That's a wrap!

Chapter 10: Files


>> Pickling time!
face Josiah Wang

Just like with JSON files, you pickle with pickle.dump(obj, file), and unpickle with pickle.load(file). That’s it, really! Just
remember that file needs to be a binary file .
import pickle

courses = {
70053: {"lecturer": "Josiah Wang", "title": "Python Programming"},
70051: {"lecturer": "Robert Craven", "title": "Symbolic AI"}
}

# Save courses to disk. Note binary mode!


with open("courses.pkl", "wb") as file:
pickle.dump(courses, file)
1
2 # Load courses from disk. Again, it is a binary file!
3 with open("courses.pkl", "rb") as file:
4 pickled_courses = pickle.load(file)
5
6 print(pickled_courses)
7 ## {70053: {'lecturer': 'Josiah Wang', 'title': 'Python Programming'},
8 ## 70051: {'lecturer': 'Robert Craven', 'title': 'Symbolic AI'}}
9
10 print(type(pickled_courses)) ## <class 'dict'>
11
12 print(courses == pickled_courses) ## True
13
14
15
16
17
18
19
20
21
22

Exercise
Here is a quick exercise. Your task:
pickle vector in the code below and save it as vectors.pkl.
then load the vector back from the file you just saved, and examine that the results are the same as
expected.
Note that this time you are pickling something more complex: a list of Vectors (your custom class).
import pickle

1 class Vector:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def __str__(self):
7 return f"Vector ({self.x}, {self.y})"
8
9 def __repr__(self):
10 """ This makes the unique string representation
11 of the object instance look more readable
12 """
13 return str(self)
14
15
16 vector1 = Vector(2, 3)
17 vector2 = Vector(4, 3)
18 vector = [vector1, vector2]
19
20 # TODO: Save vector to disk.
21 ????
22
23 # TODO: Load pickled file that you saved earlier from disk
24 pickled_vectors = ????
25
26 print(pickled_vectors) ## [Vector (2, 3), Vector (4, 3)]
27
28 print(type(pickled_vectors)) ## <class 'list'>
29
30

Peek at solution

Previous Next 

Page designed by Josiah Wang Department of Computing | Imperial College London

You might also like