Question:

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. Structure of Peripheral.csv:

\begin{tabular}{|c|c|c|} \hline \textbf{P\_id} & \textbf{P\_name} & \textbf{Price} \\ \hline \end{tabular}

  • P\_id is the Peripheral device ID (integer).
  • P\_name is the Peripheral device name (string).
  • Price is the Peripheral device price (integer).

Sangeeta wants to write the following user-defined functions:

  1. Add\_Device(): To accept a record from the user and add it to the CSV file, Peripheral.csv.
  2. Count\_Device(): To count and display the number of peripheral devices whose price is less than 1000.

Show Hint

Use csv.writer to write data to a CSV file and csv.reader to read data from a CSV file. Handle exceptions for invalid or header rows when processing numeric values.

Updated On: Jan 21, 2025
Hide Solution
collegedunia
Verified By Collegedunia

Solution and Explanation

The Add_Device() function:

  • Opens the file Peripheral.csv in append mode.
  • Accepts the details of the peripheral device (P_id, P_name, and Price) from the user.
  • Writes the new record as a row in the CSV file using the csv.writer().

 

The Count_Device() function:

  • Opens the file Peripheral.csv in read mode.
  • Iterates through each row in the file and checks if the Price (third column) is less than 1000.
  • Increments the count for each such device and displays the total count at the end.

 

Was this answer helpful?
0
0