Skip to content
Question

Q.A file, PASSENGERS.DAT, stores the records of passengers using the following structure : [PNR, PName, BRDSTN, DESTN, FARE] where : PNR - Passenger Number (string type) PName - Passenger Name (string type) BRDSTN - Boarding Station Name (string type) DESTN - Destination Station Name (string type) FARE - Fare amount for the journey (float type) Write user defined functions in Python for the following tasks :

(i) Create() - to input data for passengers and write it in the binary file PASSENGERS.DAT.
(ii) SearchDestn(D) - to read contents from the file PASSENGERS.DAT and display the details of those Passengers whose DESTN matches with the value of D.
(iii) UpdateFare() - to increase the fare of all passengers by 5% and rewrite the updated records into the file PASSENGERS.DAT.
CBSECBSE Class XII Board 2025Subjective· 5mImportance★★★★★
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

Three Python functions to create, search by destination, and update fare records in a binary file storing passenger journey data.

The question asks you to work with a binary file that holds passenger records — a common pattern in file-handling problems where structured data (like a railway reservation system) is stored persistently. Each record is a list or tuple of five fields: PNR, passenger name, boarding station, destination, and fare. You need to write three functions: one to create and populate the file, one to filter and display records by destination, and one to apply a percentage increase to all fares and save the changes back.

Binary files in Python are typically handled using the pickle module, which serializes Python objects (lists, dictionaries, tuples) into a byte stream and deserializes them on reading. Unlike text files, you cannot simply append a line; you read the entire collection of records, modify it in memory, and write it back if updates are needed.

(i) Create() — Writing records to the file

This function repeatedly prompts the user for passenger details and writes each record to PASSENGERS.DAT in binary mode. You open the file in write-binary mode ('wb' or 'ab' if appending), collect the five fields as input, pack them into a list, and use pickle.dump() to serialize and store each record.

import pickle

def Create():
    with open('PASSENGERS.DAT', 'wb') as f:
        while True:
            pnr = input("Enter PNR (or 'stop' to finish): ")
            if pnr.lower() == 'stop':
                break
            pname = input("Enter Passenger Name: ")
            brdstn = input("Enter Boarding Station: ")
            destn = input("Enter Destination: ")
            fare = float(input("Enter Fare: "))
            
            record = [pnr, pname, brdstn, destn, fare]
            pickle.dump(record, f)
    print("Records written successfully.")
Note

Opening in 'wb' mode overwrites any existing file. If you want to add records to an existing file without erasing it, use 'ab' (append-binary) instead.

Each call to pickle.dump(record, f) writes one record; the loop continues until the user types "stop". The file now contains a sequence of pickled lists, one after another.

(ii) SearchDestn(D) — Filtering by destination

This function reads all records from the file and displays only those whose destination matches the parameter D. You open the file in read-binary mode ('rb'), loop through it using pickle.load() until you hit the end (catching EOFError), and print records where the fourth field equals D.

def SearchDestn(D):
    try:
        with open('PASSENGERS.DAT', 'rb') as f:
            found = False
            while True:
                try:
                    record = pickle.load(f)
                    if record[3] == D:  # DESTN is at index 3
                        print(f"PNR: {record[0]}, Name: {record[1]}, "
                              f"Boarding: {record[2]}, Destination: {record[3]}, "
                              f"Fare: {record[4]}")
                        found = True
                except EOFError:
                    break
            if not found:
                print(f"No passengers found traveling to {D}.")
    except FileNotFoundError:
        print("File PASSENGERS.DAT does not exist.")

The inner try-except EOFError is the standard idiom for reading a pickle file of unknown length: pickle.load() raises EOFError when there are no more objects to read. The outer try-except FileNotFoundError handles the case where the file hasn't been created yet.

Important

Always use a nested try-except when reading pickled files: the inner one catches EOFError to stop reading, the outer one catches FileNotFoundError or IOError to handle missing files gracefully.

(iii) UpdateFare() — Increasing all fares by 5%

This function reads all records, increases each fare by 5%, and writes the modified list back to the file. Because binary files do not support in-place editing of individual records, you must load all records into a list, update them in memory, then rewrite the entire file.

def UpdateFare():
    try:
        with open('PASSENGERS.DAT', 'rb') as f:
            records = [] …

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.