Skip to content

Summarise a CSV file

csv.parse reads CSV (quotes, commas and line breaks inside quoted fields included) into rows of text. Turning a field into a number is a separate step, and a field that is not a number is reported with its line instead of being counted as zero.

import csv
let data = "region,product,amount\nnorth,tea,12.50\nsouth,\"coffee, dark\",8.00\nnorth,coffee,4.25\nsouth,tea,oops\n"
let rows = try csv.parse(&data)
let header = &rows[0]
let amount_at = header.index_of("amount").unwrap()
let region_at = header.index_of("region").unwrap()
let mut totals: Map<Str, f64> = Map.new()
for i in 1..rows.len() {
let row = &rows[i]
match row[amount_at].to_f64() {
Some(amount) => {
let before = *totals.get(row[region_at].clone()).unwrap_or(&0.0)
totals.insert(row[region_at].clone(), before + amount)
}
None => print(f"line {i + 1}: not an amount: {row[amount_at]}")
}
}
let mut regions = totals.keys()
regions.sort()
for r in &regions {
print(f"{r:<6} {totals.get(r.clone()).unwrap():>7.2}")
}
print(csv.text(&[["note", "has, comma"]]).trim())
line 5: not an amount: oops
north 16.75
south 8.00
note,"has, comma"

csv.text writes rows back out and quotes fields where needed. For semicolon- or tab-separated files, use csv.parse_with(&text, ';').