Class XII: Python Data File Handling | Binary Files

Search a record from binary file using employee code

 

import pickle
import os

#function definition
def search_empno():
     try:
          z=0
          tr=int(input("Enter empno to search "))
          f=open("emp","rb")
          print("Empno","Name","Salary")
          while True:
               rec=pickle.load(f)
               if rec[0]==tr:
                    z=1
                    print(rec[0],rec[1],rec[2])

     
     except EOFError:
          f.close()
          if z==0:
               print("Record not found")
     except IOError:
          print("Unable to open the file")

#function calling
search_empno()

Search a record from binary file using employee Name

 

import pickle
import os

#function definition
def search_name():
     try:
          z=0
          tn=input("Enter Name to search ")
          tn=tn.upper()
          f=open("emp","rb")
          print("Empno","Name","Salary")
          while True:
               rec=pickle.load(f)
               if rec[1]==tn:
                    z=1
                    print(rec[0],rec[1],rec[2])
     
     except EOFError:
          f.close()
          if z==0:
               print("Record not found")
     except IOError:
          print("Unable to open the file")

#function calling
search_name()