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.
1 2 3 4 5 6 7 8 910111213141516171819202122
importpicklecourses={70053:{"lecturer":"Josiah Wang","title":"Python Programming"},70051:{"lecturer":"Robert Craven","title":"Symbolic AI"}}# Save courses to disk. Note binary mode!withopen("courses.pkl","wb")asfile:pickle.dump(courses,file)# Load courses from disk. Again, it is a binary file!withopen("courses.pkl","rb")asfile:pickled_courses=pickle.load(file)print(pickled_courses)## {70053: {'lecturer': 'Josiah Wang', 'title': 'Python Programming'}, ## 70051: {'lecturer': 'Robert Craven', 'title': 'Symbolic AI'}} print(type(pickled_courses))## <class 'dict'> print(courses==pickled_courses)## True
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).
importpickleclassVector:def__init__(self,x,y):self.x=xself.y=ydef__str__(self):returnf"Vector ({self.x}, {self.y})"def__repr__(self):""" This makes the unique string representation of the object instance look more readable """returnstr(self)vector1=Vector(2,3)vector2=Vector(4,3)vector=[vector1,vector2]# TODO: Save vector to disk.????# TODO: Load pickled file that you saved earlier from diskpickled_vectors=????print(pickled_vectors)## [Vector (2, 3), Vector (4, 3)]print(type(pickled_vectors))## <class 'list'>
importpickleclassVector:def__init__(self,x,y):self.x=xself.y=ydef__str__(self):returnf"Vector ({self.x}, {self.y})"def__repr__(self):""" This makes the unique string representation of the object instance look more readable """returnstr(self)vector1=Vector(2,3)vector2=Vector(4,3)vector=[vector1,vector2]# Save vector to disk.withopen("vectors.pkl","wb")asfile:pickle.dump(vector,file)# Load pickled file that you saved earlier from diskwithopen("vectors.pkl","rb")asfile:pickled_vectors=pickle.load(file)print(pickled_vectors)## [Vector (2, 3), Vector (4, 3)]print(type(pickled_vectors))## <class 'list'>