Previous Index Next

Pickling

Pickling is the act of converting objects to a stream of bytes. You can use in-built module pickle to flatten complex object hierarchies into a byte stream. Unpickling is the inverse operation, whereby a byte stream is converted back into an object hierarchy. Pickling is alternatively known as "serialization", "marshalling", or "flattening".

To serialize (pickle) an object hierarchy, you simply call the dump() function. Similarly, to de-serialize a data stream, you call the load() function. You can pickle any object like integers, strings, tuples, lists, dictionaries, etc. and save it in a binary file.

The dump() Method

The dump() method is used to pickle object for writing data in a binary file. Syntax of dump() is as follows:

dump(data_object, file_object)

The following Pyhton program writes the record of a student (roll_no, name, gender and marks) in the binary file named school.dat using the dump().

import pickle
#create a list
record = [1,"Anu",'F', 16] 
#open file in binary mode for writing.
outfile = open('school.dat', 'wb')
#serialize the object and writing to file
pickle.dump(record, outfile)
#close the file
outfile.close()

The load() method

The load() method is used to load(unpickle) object from a binary file. Syntax of load() is as follows:

data_object = load(file_object)

The following program demonstrates how to read data from binary file and unpickle it.

import pickle
#open file in binary mode for reading
infile = open('school.dat', 'rb')
#reading the oject from file
record = pickle.load(infile)
#display the phonebook
print(record)
#close the file
infile.close()

Reading all records of binary file using pickle module

The Following add_record() function accepts a record of an employee of following format: [empcode, name, salary] from the user and appends it in the binary file. The read_records() function reads record from the binary file and displayed on the screen using the same object. If the end of the file is already reached, the load function will raise an EOFError exception. The user may enter as many records by calling add_record() function number of times.

import pickle

def add_record():
    #open file in binary mode for writing.
    outfile = open('emp.dat', 'ab')
    #Taking input from user.
    empcode = int(input('Enter Employee code: '))
    name = input('Enter Employee name: ')
    salary = int(input('Enter salary: '))
    #Store data in list
    employee = [empcode,name,salary]
    #serialize the object and writing to file
    pickle.dump(employee, outfile)
    #close the file
    outfile.close()

def read_records():
    #open file in binary mode for reading
    infile = open('emp.dat', 'rb')
    #read to the end of file.
    try:
        while True:
            #reading the oject from file
            employee = pickle.load(infile)
            #display the object
            print('Employee code:', employee[0])
            print('Employee name:', employee[1])
            print('Salary:', employee[2])
    except EOFError:
        pass
    #close the file
    infile.close()


Previous Index Next