Test Index
CBSE Class 12 Computer Science 2026 Paper Compartment
© examsnet.com
Question : 33 of 37
Marks:
+1,
-0
A CSV file named "ORDERS.CSV" contains records of customer orders placed on an e-commerce platform. The structure of each record is as follows :
[OrderID, CustomerID, OrderDate, TotalAmount, OrderStatus]A sample row for the CSV file is given below for reference :
['ORD001','C101','2024-05-20',150.75,'Shipped']Write the following Python function definitions to perform the specified tasks with the CSV file :(i) RecentOrders(): This function should read the rows from the CSV file and display the OrderID and TotalAmount for all orders placed in the year '2024'.(ii) AddOrder(newOrder): This function should write data at the end of the CSV file. The record is passed as argument to the function.
Solution:
Concept: The
csv module reads a CSV file row by row with csv.reader() (each row is a list of strings) and writes a list as one row with csv.writer().writerow(). Mode "r" reads; mode "a" (append) adds at the end without erasing old data. newline="" prevents blank lines between rows on Windows.import csv# (i)def RecentOrders(): with open("ORDERS.CSV", "r", newline="") as F: R = csv.reader(F) for row in R: if row[2].startswith("2024"): print("OrderID:", row[0], "TotalAmount:", row[3])# (ii)def AddOrder(newOrder): with open("ORDERS.CSV", "a", newline="") as F: W = csv.writer(F) W.writerow(newOrder)Explanation:(i) In each row, index 0 is OrderID, 2 is OrderDate and 3 is TotalAmount. The date is a string like '2024-05-20', so the year is its first four characters: row[2].startswith("2024") (or row[2][:4] == "2024"). For the sample row the function prints OrderID: ORD001 TotalAmount: 150.75.(ii) Opening in append mode places the new record after the existing ones; writerow() writes the list passed in, e.g. AddOrder(['ORD002','C102','2024-06-01',99.5,'Pending']).Key point: Opening with "w" in AddOrder would erase all earlier orders; the task says "at the end", so "a" is required.© examsnet.com
Go to Question: