Class XII: Python Data File Handling | Binary Files

Delete a record from binary file using roll number

1. open the binary file in read mode and open a “temp” file in write mode
2. if file does not exist then an error will be displayed
3. Take input for the roll number to delete
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 current record being traversed then write the record in the “temp” file.
9. When EOF is reached close both the files.
10. if record is found then after the files have been close remove the sourse file and rename the “temp” file with the name of source file.

import pickle
import os

#function definition
def delete_roll():
	try:
		z=0
		tr=int(input("Enter roll no to delete "))
		f=open("stud","rb")
		tf=open("temp","wb")
		print("Roll","Name","Per")
		while True:
			rec=pickle.load(f)
			if rec[0]==tr:
				z=1
				print(rec[0],rec[1],rec[2])
			else:
				pickle.dump(rec,tf)

	
	except EOFError:
		f.close()
		tf.close()
		if z==0:
			print("Record not found")
		else:
			os.remove("stud")
			os.rename("temp","stud")

	except IOError:
		print("Unable to open the file")

#function calling
delete_roll()

Update a record from binary file using roll number

1. open the binary file in read mode and open a “temp” file in write mode
2. if file does not exist then an error will be displayed
3. Take input for the roll number to delete
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 and take input for new data
8. if roll number does not match with current record being traversed then write the record in the “temp” file.
9. When EOF is reached close both the files.
10. if record is found then after the files have been close remove the sourse file and rename the “temp” file with the name of source file.

import pickle
import os

#function definition
def update_roll():
	try:
		z=0
		tr=int(input("Enter roll no to update "))
		f=open("stud","rb")
		tf=open("temp","wb")
		print("Roll","Name","Per")
		while True:
			rec=pickle.load(f)
			if rec[0]==tr:
				z=1
				print("Old Record")
				print(rec[0],rec[1],rec[2])
				print("Enter new data ")
				roll=int(input("Enter roll no "))
				name=input("Enter name ")
				name=name.upper()
				per=float(input("Enter per "))
				rec=[roll,name,per]
			pickle.dump(rec,tf)

	
	except EOFError:
		f.close()
		tf.close()
		if z==0:
			print("Record not found")
		else:
			os.remove("stud")
			os.rename("temp","stud")

	except IOError:
		print("Unable to open the file")

#function calling
update_roll()