
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:
- normalizes keys (
key.strip().lower()), - strips values,
- 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
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
nameandisland("ada"becomes"Ada"); fuelbecomes anint; skip any row whose name is empty or whose fuel isn't a whole number (usestr.isdigit()).
to_csv(rows)writes rows back as CSV text with the headername,island,fueland"\n"line endings.
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
nameandisland("ada"becomes"Ada"); fuelbecomes anint; skip any row whose name is empty or whose fuel isn't a whole number (usestr.isdigit()).
to_csv(rows)writes rows back as CSV text with the headername,island,fueland"\n"line endings.
main.py Python sleeping
Press Run to try your code, then Check to test it.