Computer Science
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
Related Questions
Consider the following definition of dictionary Staff, write a method in python to search and display content in a pickled file staff.dat, where Staffcode key of the dictionary is matching with 'S0105'.
Staff = {'Staffcode': ..............., 'Name' = ...............}
Considering the following definition of dictionary COMPANY, write a method in Python to search and display the content in a pickled file COMPANY.DAT, where CompID key of the dictionary is matching with the value '1005'.
Company = {'CompID' = ........., 'CName' = ........., 'Turnover' = .........}
A binary file "Book.dat" has structure [BookNo, Book_Name, Author, Price].
(i) Write a user defined function CreateFile() to input data for a record and add to Book.dat.
(ii) Write a function CountRec(Author) in Python which accepts the Author name as parameter and count and return number of books by the given Author are stored in the binary file "Book.dat"
Write a function Show_words() in python to read the content of a text file 'NOTES.TXT' and display only such lines of the file which have exactly 5 words in them.
Example, if the file contains :
This is a sample file.
The file contains many sentences.
But need only sentences which have only 5 words.Then the function should display the output as :
This is a sample file.
The file contains many sentences.