Unit 12Pickling and Unpickling Data

The module pickle implements serialization—saving arbitrary Python data structures into a file and reading them back as a Python expression. You can read a pickled expression from the file with any Python program, but not with a program written in another language (unless an implementation of the pickle protocol exists in that language).

You must open a pickle file for reading or writing in binary mode:

 # Dump an object into a file
 with​ open(​"myData.pickle"​, ​"wb"​) ​as​ oFile:
  pickle.dump(object, oFile)
 
 # Load the same object back
 with​ open(​"myData.pickle"​, ​"rb"​) ​as​ iFile:
  object = pickle.load(iFile)

You can store more than one object in a pickle file. The function load either ...

Get Data Science Essentials in Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.