Search binary file for string in python

Write a python program to search binary file for student record with Practical Example

Program Logic:

  • Import pickle module in program using import statement
  • Ask user to enter roll number of student using input method and store it in variable say ‘roll’
  • Open binary file ‘student.dat’ in read mode using open function and store it in file object ‘file’
  • Pass binary file name and rb mode to open method
  • Read content of binary file using pickle.load() method and store it in variable ‘filedata’
  • Close binary file using close function
  • Set found variable to zero
  • Iterate through student data line by line using for loop
  • Check whether roll number present in file or not using if condition within for loop
  • If condition is TRUE then set found variable to one
  • Display name of student using print function
  • Come out of for loop using break statement
  • Display message “Record not found” using print function when found variable set to zero

Below is Implementation code / Source code

import pickle
roll = input("Enter roll number whose record you want to search in binary file:")
file = open("student.dat","rb")
filedata = pickle.load(file)
file.close()
found = 0
for x in filedata:
    if roll in x["roll"]:
        found = 1
        print("Name of the student is :", x["sname"])
        break
if found == 0:       
        print("Record not found")

Output:

Enter roll number whose record you want to search in binary file:15
Name of the student is : Lumbini

Below is snapshot of executable code with output

<