(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.