Question:

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.
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

(i)
The following function will read the file and display all records of patients whose disease is Cancer. It uses the csv.reader() to parse the file and filters based on 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 reads the rows as lists.
- row[1] gives the disease, which is checked against "cancer" (converted to lowercase for safety).
- Only matching rows are printed.
- A try-except block handles the case when the file does not exist.

(ii)
This function counts how many records (rows) exist in the CSV file using a counter 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 file is opened and read line by line.
- For each record encountered, count is incremented.
- If the file is missing, the function returns 0 and prints an error message.
Was this answer helpful?
0
0

Top Questions on Programming in Python

View More Questions