Update binary file in python using pickle

Serialization (Also called Pickling): The process of converting Python object hierarchy into byte stream so that it can be written into a file.

De-Serialization (Also called Unpickling): The inverse of Pickling where a byte stream is converted into an object hierarchy. Unpickling produces the exact copy of original object.

  1. First import pickle module
  2. Use dump( ) and load( ) methods of pickle module to perform read and write operations on binary file.

File Opening Modes:

wb writing only. Overwrites the binary file if exists. If not, creates a new binary file for writing.

wb+ both writing and reading. Overwrites the binary file if exits. If not, creates a new binary file for writing.

rb reading only. Sets file pointer at the beginning of the binary file.

rb+ both reading and writing. Sets file pointer at the beginning of the binary file

ab for appending. Move file pointer at end of the binary file. Creates new file for writing, if not exist

ab+ for both appending and reading. Move file pointer at end. If the binary file does not exist, it creates a new file for reading and writing.

  1. Writing onto a Binary File : Pickling

Output:

2. Write a program to open the file EMP.dat(Created in previous program), read the objects written in it and display them.

Output:

3. Write a program to append two employee records to file created in previous program by getting data from the user.

Output:

Accessing and manipulating location of file pointer:

Python provides two functions to manipulate the position of file pointer and thus user can read and write from desired position.

The tell( ) function:

The tell( ) function returns the current position of the file pointer in the file.

.tell( )

The seek( ) function:

The seek ( ) function changes the position of the file pointer by placing the file pointer at the specified position in the open file.

.seek( offset[,mode])

where

offset =======>is number specifying number of bytes

mode =======> is number 0 or 1 or 2

0 for beginning of file

1 current position of file pointer

2 end of file

4. Write a program to open the file EMP.dat(Created in previous program), read and modify the name empno1207 to new vijay7 and display them.

Output:

Previous Index Next

Solved Examples - Pickle list object

Question 2

Write a menu driven program in Python that asks the user to add, display, and search records of employee stored in a binary file. The employee record contains employee code, name and salary. It should be stored in a list object. Your program should pickle the object and save it to a binary file.

Program (employee-database.py)

import pickle

def set_data():
    empcode = int(input('Enter Employee code: '))
    name = input('Enter Employee name: ')
    salary = int(input('Enter salary: '))
    print()
    
    #create a list
    employee = [empcode,name,salary]
    
    return employee


def display_data(employee):
    print('Employee code:', employee[0])
    print('Employee name:', employee[1])
    print('Salary:', employee[2])
    print()


def write_record():
    #open file in binary mode for writing.
    outfile = open('emp.dat', 'ab')

    #serialize the object and writing to file
    pickle.dump(set_data(), 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.
    while True:
        try:
            #reading the oject from file
            employee = pickle.load(infile)

            #display the object
            display_data(employee)
        except EOFError:
            break

    #close the file
    infile.close()

def search_record():
    infile = open('emp.dat', 'rb')
    empcode = int(input('Enter employee code to search: '))
    flag = False
    
    #read to the end of file.
    while True:
        try:
            #reading the oject from file
            employee = pickle.load(infile)

            #display record if found and set flag
            if employee[0] == empcode:
                display_data(employee)
                flag = True
                break
            
        except EOFError:
            break

    if flag == False:
        print('Record not Found')
        print()
        
    #close the file
    infile.close()

def show_choices():
    print('Menu')
    print('1. Add Record')
    print('2. Display Records')
    print('3. Search a Record')
    print('4. Exit')

def main():
    while(True):
        show_choices()
        choice = input('Enter choice(1-4): ')
        print()
        
        if choice == '1':
            write_record()
            
        elif choice == '2':
            read_records()

        elif choice == '3':
            search_record()

        elif choice == '4':
            break
        
        else:
            print('Invalid input')
            
#call the main function.
main()

Output

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1

Enter Employee code: 100
Enter Employee name: Deepak
Enter salary: 23000

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 1

Enter Employee code: 101
Enter Employee name: Saksham
Enter salary: 98000

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 2

Employee code: 100
Employee name: Deepak
Salary: 23000

Employee code: 101
Employee name: Saksham
Salary: 98000

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 3

Enter employee code to search: 101
Employee code: 101
Employee name: Saksham
Salary: 98000

Menu
1. Add Record
2. Display Records
3. Search a Record
4. Exit
Enter choice(1-4): 4

>>>

Previous Index Next

How do you update a binary record in Python?

Give value of roll number from user using input() function and store it in variable say roll. Open binary file say 'student. dat' in rb+( read and binary mode) and store it in file object say 'file' Use load method to read binary file data and pass file object say 'file' as an argument to load method of pickle module.

How do you append binary data in Python using pickle?

Append data in Binary File.
Open the file in append mode using “ab” Ex.: f = open (“file. dat”,”ab”).
Enter data to append..
Append entered data into the dictionary/list object..
Use pickle. dump() method to write the dictionary/list data..
Close the file..

Which method of pickle module is used to write on to a binary file?

dump(object , file_handler) - used to write any object to the binary file.

How do I read a binary file in python pickle?

To read from a binary file, use the Unpickling process in which you need to use a pickle. load() function. To write into a binary file, we have to use pickling by importing the pickle module. To read from a binary file, we need to import the PICKLE module and, from that module, use the load() function.