Pickle Module, Dump() & Load() in Binary Files in Python

python-video-tutorials

Some Important Points on Binary Files: Most of the files are available in our computer system are Binary Files. Some example of binary files are: images, videos, audio, archive and executable files etc. We cannot read or open the Binary Files in normal text editor. Binary files are only understood by a computer or a machines.

pickling-and-unpickling-in-python

Pickling: The process of converting the structure (lists and dictionary etc.) into a byte stream just before writing to the file. This is also called as object serialization.

pickling-in-python

dump() function: We use dump() method to perform pickling operation on our Binary Files. It returns the object representation in byte mode. The dump() method belongs to pickle module.

Syntax:

#pickling_in_python
import pickle

pickle.dump(object,file)

Example 1:

#Example_pickling_in_python

import pickle

def write():
    file = open("binary.dat",'wb')
    x = [1,2,3,4,5]    #data we wrote in file
    pickle.dump(x,file)
    file.close()

write()

Output data stored in file:
binary-file-in-python

Note: Hence we can observe the output that what data we wrote and what was inserted in our file. Actually data stored is correct but it has been stored in binary format which is bot readable by humans.


Unpickling: 
The reverse conversion of byte stream back to the structure (lists, dictionary, tuples etc.) refers to unpickling. Basically it is the reverse operation of pickling. This is also called de-serialization. We use load() method for unpickling. This load() function/method also belongs to pickle module.

unpickling-in-python

load() function: In pickle module, load() function is used to read data from a binary file or file object.

Syntax:

#Syntax_unpickling_in_python

import pickle

pickle.load(file)

Example 2: We will take the above file (example 1) that we have discussed and wrote data into a binary file. Let’s try to perform reverse operation on that file to read what data it is storing.

#Example_unpickling
import pickle

def read():
    file = open("binary.dat",'rb')
    data = pickle.load(file)
    file.close()
    print(data)

read()

Output:

[1, 2, 3, 4, 5]

unpickling-in-python-2

So, here our output is same that we have wrote in our binary file (example 1). Hence we can now differentiate between pickling and unpickling.