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.
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'>