Test Index

File Handling in Python Get it on Google PlayDownload on the App Store CBSE Board Videos

© examsnet.com
Question : 20 of 37
Marks: +1, -0
Sangeeta is a Python programmer working in a computer hardware company. She has to maintain the records of the peripheral devices. She created a csv file named Peripheral.csv, to store the details. The structure of Peripheral.csv is :
[P_id,P_name,Price]
where
P_id is Peripheral device ID (integer)
P_name is Peripheral device name (String)
Price is Peripheral device price (integer)
Sangeeta wants to write the following user defined functions :
Add_Device() : to accept a record from the user and add it to a csv file, Peripheral.csv.
Count_Device() : To count and display number of peripheral devices whose price is less than 1000.
[CBSE 2024 Set 4]
Solution:  
import csv
def Add_Device():
F = open("Peripheral.csv", "a", newline="") # append mode
W = csv.writer(F)
P_id = int(input("Enter Peripheral device ID: "))
P_name = input("Enter Peripheral device name: ")
Price = int(input("Enter price: "))
W.writerow([P_id, P_name, Price]) # write one record
F.close()
def Count_Device():
F = open("Peripheral.csv", "r", newline="")
R = csv.reader(F)
Count = 0
for rec in R: # rec = [P_id, P_name, Price]
if int(rec[2]) < 1000:
Count = Count + 1
print("Number of devices with price less than 1000:", Count)
F.close()
Explanation:
Add_Device(): the file is opened in append mode "a" so that old records are kept; newline="" avoids blank lines between rows; writerow() writes the record as one comma-separated line.
Count_Device(): csv.reader returns each line as a list of strings, so the price rec[2] is converted with int() before it is compared with 1000.
© examsnet.com
Advertisements
Go to Question: