Question:medium

A CSV file "P_record.csv" contains the records of patients in a hospital. Each record of the file contains the following data:
- Name of a patient
- Disease
- Number of days patient is admitted
- Amount

For example, a sample record of the file may be:
["Gunjan", "Jaundice", 4, 15000]

Write the following Python functions to perform the specified operations on this file:

(i) Write a function read_data() which reads all the data from the file and displays the details of all the 'Cancer' patients.

(ii) Write a function count_rec() which counts and returns the number of records in the file.

Show Hint

Use csv.reader() to work with CSV files in Python.
Index-based filtering (like row[1]) helps extract specific fields.
Always handle missing files with try-except.
Looping through rows gives you an easy way to count records or apply filters.
Updated On: Jan 14, 2026
Show Solution

Solution and Explanation

(i)
This function reads a CSV file and displays all patient records diagnosed with Cancer. It utilizes csv.reader() for parsing and filters records based on the disease listed in the second column.
def read_data():
    try:
        import csv
        with open("P_record.csv", "r") as f:
            reader = csv.reader(f)
            for row in reader:
                if row[1].lower() == "cancer":
                    print(row)
    except FileNotFoundError:
        print("File not found.")
Explanation:
- csv.reader processes each row as a list.
- row[1] accesses the disease entry, which is compared to "cancer" after converting to lowercase for case-insensitivity.
- Only rows where the disease matches "cancer" are outputted.
- A try-except block is implemented to gracefully handle the absence of the specified file.

(ii)
This function determines the total number of records (rows) present in the CSV file by employing a counter within a loop.
def count_rec():
    count = 0
    try:
        import csv
        with open("P_record.csv", "r") as f:
            reader = csv.reader(f)
            for row in reader:
                count += 1
        return count
    except FileNotFoundError:
        print("File not found.")
        return 0
Explanation:
- The CSV file is opened and iterated through record by record.
- The count variable is incremented for each record processed.
- In the event that the file is not found, the function returns 0 and displays an error message.
Was this answer helpful?
0