(i) Function to create binary file with passenger records:
import pickle
def Create():
with open("PASSENGERS.DAT", "wb") as f:
n = int(input("Enter number of passengers: "))
for i in range(n):
PNR = input("Enter PNR: ")
PName = input("Enter Name: ")
BRDSTN = input("Enter Boarding Station: ")
DESTN = input("Enter Destination Station: ")
FARE = float(input("Enter Fare: "))
rec = [PNR, PName, BRDSTN, DESTN, FARE]
pickle.dump(rec, f)
Explanation:
-
pickle.dump() is used to write each record as a list into the binary file.
- Each record is collected using
input() and converted to the correct type.
- The file is opened in write-binary mode using
"wb".
(ii) Function to search by DESTN and display matching records:
def SearchDestn(D):
try:
with open("PASSENGERS.DAT", "rb") as f:
print("Passengers going to", D)
while True:
rec = pickle.load(f)
if rec[3].lower() == D.lower():
print(rec)
except EOFError:
pass
except FileNotFoundError:
print("File not found.")
Explanation:
- Records are read one by one using
pickle.load().
- The loop runs until an
EOFError is encountered.
- Destination field
rec[3] is compared (case-insensitive).
(iii) Function to update fare of all passengers by 5% and rewrite file:
def UpdateFare():
updated = []
try:
with open("PASSENGERS.DAT", "rb") as f:
while True:
rec = pickle.load(f)
rec[4] = round(rec[4] * 1.05, 2)
updated.append(rec)
except EOFError:
pass
except FileNotFoundError:
print("File not found.")
return
with open("PASSENGERS.DAT", "wb") as f:
for rec in updated:
pickle.dump(rec, f)
Explanation:
- Each record’s fare (
rec[4]) is increased by 5% using multiplication.
- All updated records are stored in a list, then written back using
"wb" mode.
-
round(..., 2) ensures two decimal precision.