Given a binary file containing the students information, in the form of a dictionary. The task is to read the Student data from the binary file and print the contents to the std out.
The Student data is a dictionary containing student name and marks obtained.
Let's you first understand the program to open the binary file and write the Student data then let's try to read it
Write a Python Program to Write Student Data From a Binary File stu.dat
In order to read and write binary files we need to use the pickle module. Let's use open function call and pass the filename stu.dat as input argument with the file mode to open the file in write and binary mode “wb”.
import pickle
fd_write = open("stu.dat","wb")
student = {"name": "jack", "marks": 23}
pickle.dump(student,fd_write)
fd_write.close()
Take a Student dictionary containing info of Student name and student marks obtained and use the pickle.dump() Function to write the contents of this tree to the binary file. then using the file descriptor close the file.
This will write the contents of student details into a binary file
Now let's understand how to open a binary file and read the contents of the file containing Student data and print on the console.
Write a Python Program to Read Student Data From a Binary File stu.dat
Use the pickle module by importing into your program. Once we import the required library use try block to to open a binary file stu.dat in the read binary mode ”rb”.
If the file is not found, catch an exception file not found error print an error message and exit the program.
import pickle
try:
fd = open("stu.dat" , "rb")
except FileNotFoundError:
print("Binary file not found !")
exit(-1)
Use the try block else part to read the contents of the file, Bhai again using the try block having a while loop. use pickle.load() function to read the contents of the file descriptor and print the data.
Use the end of file exception to check the end of file error, once the end of file exception is caught use close function to close the file descriptor.
else:
try:
print("Student details are ...")
while True:
data = pickle.load(fd)
print(data)
except EOFError:
fd.close()
Complete Program
===========================
import pickle
try:
fd = open("stu.dat" , "rb")
except FileNotFoundError:
print("Binary file not found !")
exit(-1)
else:
try:
print("Student details are ...")
while True:
data = pickle.load(fd)
print(data)
except EOFError:
fd.close()
OUTPUT
=======================
Student details are ...
{'name': 'jack', 'marks': 23}
Conclusion
===================
Try running the program by adding extra student details like name1, name2, name3 etc and also the marks obtained by them.
In the comment section let me know if you can try writing student details using a tuple ?
0 Comments