Test Index
File Handling in Python
© examsnet.com
Question : 25 of 37
Marks:
+1,
-0
Mr. Mahesh is a Python Programmer working in a school. He has to maintain the records of the sports students. He has created a csv file named
sports.csv, to store the details. The structure of sports.csv is :[sport_id, competition, prize_won]wheresport_id, is Sport id (integer)competition is competition name (string)prize_won is (“Gold”, “Silver”, “Bronze”)Mr. Mahesh wants to write the following user-defined functions :Add_detail(): to accept the detail of a student and add to a csv file, "sports.csv".Count_Medal(): to display the name of competitions in which students have won "Gold" medal.Help him in writing the code of both the functions.[CBSE 2024 Compartment]
Solution:
import csvdef Add_detail(): f = open("sports.csv", "a", newline="") w = csv.writer(f) sport_id = int(input("Sport id: ")) competition = input("Competition: ") prize_won = input("Prize won (Gold/Silver/Bronze): ") w.writerow([sport_id, competition, prize_won]) f.close()def Count_Medal(): f = open("sports.csv", "r") r = csv.reader(f) for row in r: if row[2] == "Gold": print(row[1]) f.close()Explanation:Add_detail(): the file is opened in append mode ("a") so old records are kept; newline="" avoids blank lines between rows. The three values are read from the user and written as one row with writerow().Count_Medal(): the file is opened in read mode and csv.reader returns each row as a list of strings: row[0] = sport_id, row[1] = competition, row[2] = prize_won. When prize_won is "Gold", the competition name is displayed.© examsnet.com
Go to Question: