Test Index
CBSE Class 12 Computer Science 2025 Paper Set 4
© examsnet.com
Question : 33 of 37
Marks:
+1,
-0
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• AmountFor 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.
Solution:
Concept: Import the
csv module, open the file in read mode ("r"), and pass the file object to csv.reader(). The reader gives each line as a list of strings, e.g. ['Gunjan', 'Jaundice', '4', '15000'], so the disease is at index 1.(i)import csvdef read_data(): F = open("P_record.csv", "r", newline="") reader = csv.reader(F) for rec in reader: # rec = [name, disease, days, amount] if rec[1] == "Cancer": print(rec) F.close()(ii)def count_rec(): F = open("P_record.csv", "r", newline="") reader = csv.reader(F) count = 0 for rec in reader: # one record per row count += 1 F.close() return countread_data()print("Number of records:", count_rec())Explanation:• In (i) only rows whose second field is Cancer are printed.• In (ii) every row read is counted; len(list(csv.reader(F))) gives the same count. The function returns the number (it does not just print it), as the question asks.© examsnet.com
Go to Question: