BINARY FILE HANDLING
1 Mark Questions
1. Which file mode is used to open a binary file for both reading and
writing without truncating the file?
(a) rb
(b) wb
(c) rb+
(d) ab
Answer: c) rb+
2. What will happen if you try to load() data from a binary file that is
empty?
(a) It returns None
(b) It raises a ValueError
(c) It raises an EOFError
(d) It skips to the next record
Answer: c) It raises an EOFError
Each question has an Assertion (A) and a Reason (R). Choose the
correct option:
(A) Both Assertion and Reason are true, and Reason is the correct
explanation of Assertion.
(B) Both Assertion and Reason are true, but Reason is not the correct
explanation of Assertion.
(C) Assertion is true, but Reason is false.
(D) Assertion is false, but Reason is true.
3. Assertion (A): ab+ mode allows both appending and reading from a
binary file.
Reason (R): In ab+ mode, the file pointer is placed at the beginning of
the file.
Answer: (C)
2 Marks Questions
4. Differentiate between ab+ and wb+ modes
Answer
Feature ab+ Mode wb+ Mode
Mode Append (adds to end) Write (overwrites file)
No truncation, Truncates existing
File Truncation
preserves data file
Starts at end for
File Pointer Starts at beginning
writing
Append and read Overwrite and read
Use Case
binary files binary files
5. Differentiate between dump() and writelines() in Python.
Answer:
Point dump() writelines()
1. Used With Binary files Text files
Requires pickle
2. Module Part of standard file object
module
Serializes Python
3. Purpose Writes sequence of strings
objects
Can write any Python
4. Data Type Can only write strings
object
3 Marks Questions
6. Consider a binary file SHOP.DAT containing records in the format:
[shop_id, shop_name, revenue]
Write a function CopyHighRevenue(), that copies all records whose
revenue is greater than 100000 from SHOP.DAT to HIGH_SHOP.DAT.
Answer:
import pickle
def CopyHighRevenue():
try:
# Open input file in binary read mode
file = open("SHOP.DAT", "rb")
shops = pickle.load(file)
file.close()
# Create empty list for high revenue shops
high_revenue_shops = []
# Loop through shops and append those with revenue > 100000
for shop in shops:
if shop["revenue"] > 100000:
high_revenue_shops.append(shop)
# Write filtered shops to output file
file = open("HIGH_SHOP.DAT", "wb")
pickle.dump(high_revenue_shops, file)
file.close()
print("High revenue shops copied successfully.")
except FileNotFoundError:
print("Error: SHOP.DAT file not found.")
7. A binary file CUSTOMER.DAT has the structure:
[cust_id, name, city, balance]
where:
cust_id: Customer ID (string type)
name: Customer Name (string type)
city: City Name (string type)
balance: Account Balance (float type)
Write a user-defined function DispHighBalance(), that reads the contents
of the file CUSTOMER.DAT and displays the details of customers whose
balance is above 10000.
Answer:
import pickle
def DispHighBalance():
file = open("CUSTOMER.DAT", "rb")
try:
while True:
cust = pickle.load(file)
if cust[3] > 10000:
print(cust)
except:
file.close()
5 Marks Questions
8. A binary file TICKETS.DAT stores ticket records in the format [TicketID,
Event, Cost], where TicketID is an integer, Event is a string, and Cost is
a float. Write the following Python functions: (i) CreateTicket(): Inputs a
ticket record and writes it to the file.
(ii) DisplayEvent(E): Displays all records for the given Event.
(iii) TotalCost(): Returns the sum of costs for all tickets.
Answer:
import pickle
# (i) CreateTicket: Inputs and writes a ticket record
def CreateTicket():
F = open("TICKETS.DAT", "ab")
TicketID = int(input("Enter Ticket ID: "))
Event = input("Enter Event: ")
Cost = float(input("Enter Cost: "))
Rec = [TicketID, Event, Cost]
pickle.dump(Rec, F)
F.close()
# (ii) DisplayEvent: Displays records for given Event
def DisplayEvent(E):
try:
F = open("TICKETS.DAT", "rb")
while True:
Rec = pickle.load(F)
if Rec[1] == E:
print(Rec)
except EOFError:
F.close()
except FileNotFoundError:
print("File not found!")
# (iii) TotalCost: Returns sum of costs
def TotalCost():
total = 0
try:
F = open("TICKETS.DAT", "rb")
while True:
Rec = pickle.load(F)
total += Rec[2]
except EOFError:
F.close()
except FileNotFoundError:
print("File not found!")
return total
9. A binary file PRODUCTS.DAT stores product records in the format
[ProdID, ProdName, Price], where ProdID is an integer, ProdName is a
string, and Price is a float. Write the following Python functions:
(i) AddProduct(): Inputs a product record and writes it to the file.
(ii) SearchProdName(PName): Displays all records where ProdName
matches PName.
(iii) UpdatePrice(PID, NewPrice): Updates the price of the product with
the given ProdID to NewPrice.
Answer:
import pickle
# (i) AddProduct: Inputs and writes a product record
def AddProduct():
F = open("PRODUCTS.DAT", "ab")
ProdID = int(input("Enter Product ID: "))
ProdName = input("Enter Product Name: ")
Price = float(input("Enter Price: "))
Rec = [ProdID, ProdName, Price]
pickle.dump(Rec, F)
F.close()
# (ii) SearchProdName: Displays records matching ProdName
def SearchProdName(PName):
try:
F = open("PRODUCTS.DAT", "rb")
while True:
Rec = pickle.load(F)
if Rec[1] == PName:
print(Rec)
except EOFError:
F.close()
except FileNotFoundError:
print("File not found!")
# (iii) UpdatePrice: Updates price for given ProdID
def UpdatePrice(PID, NewPrice):
try:
F = open("PRODUCTS.DAT", "rb")
Records = []
while True:
Rec = pickle.load(F)
Records.append(Rec)
F.close()
for i in range(len(Records)):
if Records[i][0] == PID:
Records[i][2] = NewPrice
F = open("PRODUCTS.DAT", "wb")
for Rec in Records:
pickle.dump(Rec, F)
F.close()
print("Price updated!")
except FileNotFoundError:
print("File not found!")
10. A binary file MOVIES.DAT contains movie records in the format
[MovieID, Title, Rating], where MovieID is an integer, Title is a string,
and Rating is a float. Write the following Python functions:
(i) AddMovie(): Inputs a movie record and appends it to the file.
(ii) DisplayRating(R): Displays all records where Rating is greater than
or equal to R.
(iii) AverageRating(): Calculates and returns the average rating of all
movies.
Answer:
import pickle
# (i) AddMovie: Inputs and appends a movie record
def AddMovie():
F = open("MOVIES.DAT", "ab")
MovieID = int(input("Enter Movie ID: "))
Title = input("Enter Title: ")
Rating = float(input("Enter Rating: "))
Rec = [MovieID, Title, Rating]
pickle.dump(Rec, F)
F.close()
# (ii) DisplayRating: Displays records with Rating >= R
def DisplayRating(R):
try:
F = open("MOVIES.DAT", "rb")
while True:
Rec = pickle.load(F)
if Rec[2] >= R:
print(Rec)
except EOFError:
F.close()
except FileNotFoundError:
print("File not found!")
# (iii) AverageRating: Returns average rating
def AverageRating():
total = 0
count = 0
try:
F = open("MOVIES.DAT", "rb")
while True:
Rec = pickle.load(F)
total += Rec[2]
count += 1
except EOFError:
F.close()
if count == 0:
return 0
return total / count
except FileNotFoundError:
print("File not found!")
return 0