Write a python program to delete student data from binary file with Practical Example
Program Description:
This program to read binary file and delete student record from it
Program Logic:
- Include pickle module in the program by using import statement
- Enter roll number of student using the input() function and store it in a variable say ‘roll’
- Open binary file in read mode using open method and pass filename and rb+ mode to it.
- Read binary file using load() function and store it in a variable say ‘filedata’.
- Set value of found variable to zero
- Create empty list object say ‘lst’
- Use for loop to iterate through student data one by one
- Check roll number present in student record using if loop within for loop
- If condition is TRUE then append list object with student data
- If condition is FALSE then set value of found variable to 1
- Write data into list object from binary file using dump method when value of found variable is 1.
- Print error message “Roll number does not found” using print function when found variable is zero.
- Close the binary file using close() function.
- The exit of the program.
Below is implementation code/Source code
import pickle
roll = input("Enter roll number whose record you want to delete:")
file = open("student.dat","rb+")
filedata = pickle.load(file)
found = 0
lst = [ ]
for x in filedata:
if roll not in x['roll']:
lst.append(x)
else:
found = 1
if found == 1:
file.seek(0)
pickle.dump(lst,file)
print("Record Deleted")
else :
print("Roll number does not found")
file.close()
file = open("student.dat","rb")
f = pickle.load(file)
print(f)
Below is Output
Enter roll number whose record you want to delete:11 Record Deleted [{'roll': '13', 'sname': 'Sujata'}, {'roll': '15', 'sname': 'Lumbini'}]
Below is Snapshot of Executable code with Output




You can also check this too
- Python program to modify or update student data from binary file
- Python program to get mode and encoding format of file
- Python program to search specific data in binary file
- Python program to create list of email ids and write list into text file
- Python program to select word randomly from text file and store it in another file.
<