Class XII: Python Data File Handling | Binary Files

Search a record from binary file using roll number

1. open the binary file in read mode
2. if file does not exist then an error will be displayed
3. Take input for the roll number to search
4. using a while loop read a binary file
5. read a record from binary file using pickle.load()
6. compare the roll number of record read from the file
with the roll number to search
7. if roll number matches then display the record
8. if roll number does not match with any of the records
then display a message “record not found”
5. When EOF is reached close the file.

import pickle
import os

#function definition
def search_roll():
	try:
		z=0
		tr=int(input("Enter roll no to search "))
		f=open("stud","rb")
		print("Roll","Name","Per")
		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_roll()

Search a record from binary file using Name

1. open the binary file in read mode
2. if file does not exist then an error will be displayed
3. Take input for the name to search
4. using a while loop read a binary file
5. read a record from binary file using pickle.load()
6. compare the name of record read from the file
with the name to search
7. if name matches then display the record
8. if name does not match with any of the records
then display a message “record not found”
5. When EOF is reached close the file.

import pickle
import os

#function definition
def search_name():
	try:
		z=0
		tn=input("Enter Name to search ")
		tn=tn.upper()
		f=open("stud","rb")
		print("Roll","Name","Per")
		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()