Binary File Handling Programs for Class 12
1. Write and Read a List to a Binary File
import pickle
nums = [10, 20, 30, 40, 50]
with open("[Link]", "wb") as f:
[Link](nums, f)
with open("[Link]", "rb") as f:
data = [Link](f)
print("Data in file:", data)
2. Store and Read Student Records (Multiple Records)
import pickle
students = [(1, "Amit"), (2, "Sara"), (3, "Neha")]
with open("[Link]", "wb") as f:
for s in students:
[Link](s, f)
with open("[Link]", "rb") as f:
while True:
try:
rec = [Link](f)
print(rec)
except EOFError:
break
3. Search a Record in a Binary File
import pickle
roll_to_search = 2
found = False
with open("[Link]", "rb") as f:
while True:
try:
r = [Link](f)
if r[0] == roll_to_search:
print("Record found:", r)
found = True
break
except EOFError:
break
4. Count Records in a Binary File
import pickle
count = 0
with open("[Link]", "rb") as f:
while True:
try:
[Link](f)
count += 1
except EOFError:
break
print("Total records =", count)
5. Update a Record
import pickle
records = []
with open("[Link]", "rb") as f:
while True:
try:
[Link]([Link](f))
except EOFError:
break
for i in range(len(records)):
if records[i][0] == 3:
records[i] = (3, "Nidhi")
with open("[Link]", "wb") as f:
for r in records:
[Link](r, f)
6. Copy Binary File
with open("[Link]", "rb") as f1, open("[Link]", "wb") as f2:
[Link]([Link]())
7. Delete a Record
import pickle
records = []
with open("[Link]", "rb") as f:
while True:
try:
[Link]([Link](f))
except EOFError:
break
roll_to_delete = 2
records = [r for r in records if r[0] != roll_to_delete]
with open("[Link]", "wb") as f:
for r in records:
[Link](r, f)