Class - 12 CBSE Computer Science Important File Handling Questions 2025
Write a function to search and display details of all trains, whose destination is "Delhi" from a binary file "TRAIN.DAT". Assuming the binary file is containing the objects of the following dictionary type:
Train = {'Tno': ..............., 'From': ...............,'To': ...............}
Python File Handling
2 Likes
Answer
Let the dictionary contained in file "TRAIN.DAT" be as shown below:
Train1 = {'Tno': '1234', 'From': 'Mumbai', 'To': 'Delhi'}
Train2 = {'Tno': '5678', 'From': 'Chennai', 'To': 'Delhi'}
Train3 = {'Tno': '9012', 'From': 'Kolkata', 'To': 'Mumbai'}
Train4 = {'Tno': '3456', 'From': 'Delhi', 'To': 'Bangalore'}
Train5 = {'Tno': '7890', 'From': 'Pune', 'To': 'Delhi'}
import pickle
def search_trains():
found = False
try:
file = open("TRAIN.DAT", "rb")
while True:
trains = pickle.load(file)
if trains['To'] == "Delhi":
print("Train no: ", trains['Tno'])
print("From: ", trains['From'])
print("To: ", trains['To'])
found = True
except EOFError:
if found == False:
print("End of file reached. No such records found.")
else:
print("Search Successful")
file.close()
search_trains()
Output
Train no: 1234
From: Mumbai
To: Delhi
Train no: 5678
From: Chennai
To: Delhi
Train no: 7890
From: Pune
To: Delhi
Search Successful
Answered By
1 Like