Code

Cleaning a CSV

The csv module reads rows from any file-like object. For text you already have, wrap it in io.StringIO:

import csv, io

text = "name,fuel\nAda,12\nBo,7\n"
for row in csv.DictReader(io.StringIO(text)):
    print(row)   # {'name': 'Ada', 'fuel': '12'} ...

DictReader uses the header line as keys. Every value is a string, exactly as typed, including stray spaces. Real spreadsheets are messy, so a cleaning pass usually:

  1. normalizes keys (key.strip().lower()),
  2. strips values,
  3. converts types, skipping rows that don't make sense.

Writing goes through csv.DictWriter:

out = io.StringIO()
w = csv.DictWriter(out, fieldnames=["name", "fuel"],
                   lineterminator="\n")
w.writeheader()
w.writerow({"name": "Ada", "fuel": 12})
out.getvalue()   # 'name,fuel\nAda,12\n'

Assignment

  1. clean_roster(text) returns a list of dicts with keys "name", "island" and "fuel":
    • header names may have stray spaces or capitals, normalize them;
    • strip every value; title-case name and island ("ada" becomes "Ada");
    • fuel becomes an int; skip any row whose name is empty or whose fuel isn't a whole number (use str.isdigit()).
  2. to_csv(rows) writes rows back as CSV text with the header name,island,fuel and "\n" line endings.