Writing and Reading objects in Binary Files
Files that store objects as some byte stream are the binary files. Objects have a specific structure which must be maintained while storing or accessing them. Python provides a special module - the pickle module to take care of that.
The pickle module implements a fundamental, but powerful algorithm for serializing and de-serializing a Python object structure. "Pickling" is the process whereby a Python object hierarchy is converted into a byte-stream, and "unpickling" is the inverse operation, whereby a byte-stream is converted back into an object hierarchy." In this infobox you shall learn to use pickle module for reading/writing class instances.
In order to work with pickle module, you must first import it in your program using import statement :
import pickle
And then, you may use dump() and load() methods of pickle module to write and read from file respectively.
Writing Instances onto a File-Pickling
In order to write an object on to a binary file, opened in write mode, you should use dump() function as per following syntax:
pickle.dump(<object-to-be-written>, <filehandle-of-open-file>)
For instance, if you have a file open in handle fileI and you want to write a list namely list1 in the file, then you may write
pickle.dump(list1, file1)
In the same way, you may write dictionaries, class objects etc. in binary file. For instance, to write an object student of class type Student in a file open in handle file2, you may write: