Computer Science – 20.2 File Processing and Exception Handling | e-Consult
20.2 File Processing and Exception Handling (1 questions)
Model Answer 2
This solution uses the csv module to read and write CSV files, performing calculations on the data.
import csv
def calculateproductrevenue(inputfilename, outputfilename):
product_revenue = {}
try:
with open(input_filename, 'r', newline='') as infile:
reader = csv.reader(infile)
header = next(reader) # Skip the header row
for row in reader:
product_name, quantity, price = row
try:
quantity = int(quantity)
price = float(price)
except ValueError:
print(f"Warning: Invalid data in row: {row}. Skipping.")
continue
revenue = quantity * price
if productname in productrevenue:
productrevenue[productname] += revenue
else:
productrevenue[productname] = revenue
except FileNotFoundError:
print(f"Error: File '{input_filename}' not found.")
return
try:
with open(output_filename, 'w', newline='') as outfile:
writer = csv.writer(outfile)
writer.writerow(["Product Name", "Total Revenue"]) # Write header
for product, revenue in product_revenue.items():
writer.writerow([product, revenue])
except Exception as e:
print(f"Error writing to file '{output_filename}': {e}")
if name == "main":
inputfile = "salesdata.csv"
outputfile = "productrevenue.csv"
calculateproductrevenue(inputfile, outputfile)
Explanation:
- The code uses the
csvmodule to read the input CSV file. - It skips the header row.
- For each row, it extracts the product name, quantity, and price.
- It calculates the revenue for that sale.
- It aggregates the revenue for each product in the
product_revenuedictionary. - Finally, it writes the product names and their total revenue to the output CSV file.
- Error handling is included for file not found and invalid data in the input file.