Skip to content
Aabha AI Academy
Skip to reading

Python

05 Files Errors

# Profile: Python basics. StringIO gives the CSV reader file-like text.
import csv
from io import StringIO

csv_text = "topic,minutes\npython,20\ndata,not recorded\ncharts,30\n"
accepted = []
rejected = []
with StringIO(csv_text) as source:
    for line_number, row in enumerate(csv.DictReader(source), start=2):
        try:
            minutes = int(row["minutes"])
            if minutes < 0:
                raise ValueError("minutes must be non-negative")
        except ValueError:
            rejected.append({"line": line_number, "raw": row["minutes"]})
        else:
            accepted.append({"topic": row["topic"], "minutes": minutes})
print("Accepted:", accepted)
print("Rejected:", rejected)
print("Accepted minutes:", sum(row["minutes"] for row in accepted))

Download this source file