Modify or update data in binary file Python

Write a python program to modify or update student record in binary file with Practical Example

Program Description:

This program takes value of roll number from user and update student record of binary file with new roll number

Program Logic:

  • Include pickle module in program using import statement
  • 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
  • Traverse through student record one by one using for loop
  • Check requested data present in student record using if loop within for loop
  • If data is found,then set value of found variable to one.
  • Ask user to enter new data using input method
  • Append new data in list object using append method
  • Update student record with new data by writing new data into binary file using dump method when found is 1
  • Print message “Roll number does not found if found is zero.

Below is implementation code/Source code

import pickle
roll = input("Enter roll number whose name you want to update in binary file:")
file = open("student.dat","rb+")
filedata = pickle.load(file)
found = 0
lst = [ ]
for x in filedata:
    if roll in x['roll']:
        found = 1
        x['sname']=input("Enter new name :")
if found == 1:
    print("Record updated")
    print("Roll number does not exist")

Below is Snapshot of Executable code with output