Class XII: Python Data File Handling | Binary Files

Binary File to maintain student records

Student Data maintained :

roll number
name
per

To Add record in a Binary File

Points

1. if the file does not exist the create a binary file
2. if the file exits then open the file in append mode
3. Take input for roll, name and per.
4. store them in a variable rec
5. write the record in the binary file using pickle.dump()
6. close the file

import pickle
import os

#function definition
def add_record():
	try:
		if os.path.isfile("stud"):
			f=open("stud","ab")
		else:
			f=open("stud","wb")
		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,f)
		print("Record added in file")
	except EOFError:
		f.close()

#function calling
add_record()

Display all the records from binary file

1. open the binary file in read mode
2. if file does not exist then an error will be displayed
4. using a while loop read a binary file
3. read a record from binary file using pickle.load()
4. display the record
5. When EOF is reached close the file.

import pickle

#function definition
def std_dispall():
	try:
		f=open("stud","rb")
		while True:
			rec=pickle.load(f)
			print(rec)

	
	except EOFError:
		f.close()
	except IOError:
		print("Unable to open the file")

#function calling
std_dispall()

Display all the records from binary file (2nd Method)

1. open the binary file in read mode
2. if file does not exist then an error will be displayed
3. using a while loop read a binary file
4. read a record from binary file using pickle.load()
5. display the record
6. When EOF is reached close the file.

import pickle

#function definition
def std_dispall_1():
	try:
		f=open("stud","rb")
		print("Roll","Name","Per")
		while True:
			rec=pickle.load(f)
			print(rec[0],rec[1],rec[2])

	
	except EOFError:
		f.close()
	except IOError:
		print("Unable to open the file")

#function calling
std_dispall_1()