Write a python program to write student record into binary file with Practical Example
Program Description:
This program writes student records into binary file
Program Logic:
- Include pickle module in program using import statement
- Declare empty list to store the record
- Give the roll number and name of student from user one by one and store the values in variables roll and name respectively
- Create dictionary say ‘student’ and store student record one by one into it
- Use append method to write student record into empty list say’student’ and pass student dictionary as an argument to append method
- Ask user to add more record into binary file and store value in variable say ‘choice’
- If user want to add more record then take data from user using while loop
- If user do not want to add more record into binary file then skip the above process
- Collect student record from user and store in the form of list
- Open binary file say ‘student.dat’ in write and binary mode
- Write list data into binary file using dump method and pass lst and file as an argument to dump method
- Close binary file ‘student.dat’ using close() function.
Below is implementation code/Source code:
Here is program to write student record into binary file ‘student.dat’. The output is also shown below.
import pickle
lst =[]
while True:
roll = input("Enter roll number:")
name = input("Enter name of student:")
student = {"roll" :roll,"sname":name}
lst.append(student)
choice = input("Want to add more record(y/n):")
if (choice=='n'):
break
file = open("student.dat",'wb')
pickle.dump(lst,file)
file.close()
Below is snapshot of executable code with output:
