Course › Week 3 · Iterators, real data, speed › Day 4 · lesson 18 of 42 · 25 min reading + 45–60 min practice
Streaming CSV
Read a huge CSV one row at a time, and report bad rows instead of stopping.
On this page
A school-evaluation export can be a CSV of millions of rows: one row per answer, per question, per evaluation. PHP’s fgetcsv reads it a row at a time; the Rust csv crate does the same, and with serde it hands you each row as a typed struct.
The important decision today is not a function. It is what to do with a bad row. A form rejects everything on the first error; an import of 1 million rows should report the 13 bad ones and keep going.
Setup, and the sample
cargo add csv
cargo add serde --features derive
Every program below reads this survey.csv. It has two bad rows on purpose: a score written as a word, and a score of 9 on a 1-to-5 scale. The last row has a comma inside a quoted comment, which a naive split(',') would break on.
evaluation_id,school,question,score,comment
1001,Alexandria STEM,Q1,5,Clear explanations
1001,Alexandria STEM,Q2,4,
1002,Cairo Language School,Q1,3,Too fast
1002,Cairo Language School,Q2,five,
1003,Giza Primary,Q1,9,
1003,Giza Primary,Q2,2,"Needs more examples, and a slower pace"
1. Reading records
Reader::from_path opens the file and reads the first line as headers. .records() is an iterator of Result<StringRecord>: each row as a list of text fields, or the reason it could not be read.
The examples today return Box<dyn Error> from main. It means “any error type”, so ? works on a CSV error and an I/O error in the same function: the closest thing to catching \Throwable. Fine for short programs; the csv2json build uses a real error enum again.
use std::error::Error;
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = csv::Reader::from_path("survey.csv")?;
println!("headers: {:?}", reader.headers()?);
for result in reader.records() {
let record = result?;
println!("{} fields: {:?}", record.len(), record);
}
Ok(())
}
headers: StringRecord(["evaluation_id", "school", "question", "score", "comment"])
5 fields: StringRecord(["1001", "Alexandria STEM", "Q1", "5", "Clear explanations"])
5 fields: StringRecord(["1001", "Alexandria STEM", "Q2", "4", ""])
5 fields: StringRecord(["1002", "Cairo Language School", "Q1", "3", "Too fast"])
5 fields: StringRecord(["1002", "Cairo Language School", "Q2", "five", ""])
5 fields: StringRecord(["1003", "Giza Primary", "Q1", "9", ""])
5 fields: StringRecord(["1003", "Giza Primary", "Q2", "2", "Needs more examples, and a slower pace"])The quoted comment came through as one field, with the comma kept and the quotes removed. CSV quoting is the reason never to parse CSV with split.
2. Rows as structs
.deserialize() uses serde, with the same derive as in the serde lesson. Fields are matched to columns by the header names, and each value is converted to the field’s type. The type on row says which struct to build.
use std::error::Error;
use serde::Deserialize;
#[derive(Deserialize)]
struct Response {
evaluation_id: u64,
school: String,
question: String,
score: u8,
comment: Option<String>,
}
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = csv::Reader::from_path("survey.csv")?;
for result in reader.deserialize() {
let row: Response = result?;
println!(
"{} {} {}: {} {:?}",
row.evaluation_id, row.school, row.question, row.score, row.comment
);
}
Ok(())
}
1001 Alexandria STEM Q1: 5 Some("Clear explanations")
1001 Alexandria STEM Q2: 4 None
1002 Cairo Language School Q1: 3 Some("Too fast")
Error: Error(Deserialize { pos: Some(Position { byte: 157, line: 5, record: 4 }), err: DeserializeError { field: Some(3), kind: ParseInt(ParseIntError { kind: InvalidDigit }) } })
exit code 1Three rows printed, then the whole program stopped at the fourth with exit code 1: ? passed the first bad row up and ended main. Returning an error from main prints its debug form, as in the errors lesson, but everything is in it: line 5, record 4, field 3, not a number. Section 3 prints the same error as a sentence. Either way, one bad answer should not throw away a whole export.
An empty comment became None. For an Option field, the csv crate reads an empty cell as missing.
3. Report a bad row, keep going
Instead of ?, match each row. A good row is processed; a bad one is reported on stderr with its line number and counted, and the loop goes on. At the end, the program says how many rows it skipped, so a bad import never looks like a clean one.
use std::error::Error;
use serde::Deserialize;
#[derive(Deserialize)]
struct Response {
evaluation_id: u64,
school: String,
question: String,
score: u8,
comment: Option<String>,
}
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = csv::Reader::from_path("survey.csv")?;
let mut good: u64 = 0;
let mut bad: u64 = 0;
for result in reader.deserialize() {
let row: Response = match result {
Ok(row) => row,
Err(error) => {
bad += 1;
let line = error.position().map(|p| p.line()).unwrap_or(0);
eprintln!("skipped line {line}: {error}");
continue;
}
};
good += 1;
println!(
"#{} {} {}: {} {:?}",
row.evaluation_id, row.school, row.question, row.score, row.comment
);
}
eprintln!("{good} rows read, {bad} skipped");
Ok(())
}
#1001 Alexandria STEM Q1: 5 Some("Clear explanations")
#1001 Alexandria STEM Q2: 4 None
#1002 Cairo Language School Q1: 3 Some("Too fast")
#1003 Giza Primary Q1: 9 None
#1003 Giza Primary Q2: 2 Some("Needs more examples, and a slower pace")
skipped line 5: CSV deserialize error: record 4 (line: 5, byte: 157): field 3: invalid digit found in string
5 rows read, 1 skippederror.position() is an Option: errors that happen before any row is read (a missing file) have no position. .map(|p| p.line()) takes the line number out of it if it is there, and unwrap_or(0) covers the case where it is not.
Normal output goes to stdout, problems to stderr. Run it as cargo run > scores.txt and the file gets only the data, while the skipped lines still appear on screen.
4. Types are not the whole validation
The score 9 parsed fine as a u8, and it is still wrong: the scale is 1 to 5. Rules the type cannot express go in a function that returns a Result, and a row is kept only when both the conversion and the rules pass:
use std::error::Error;
use serde::Deserialize;
#[derive(Deserialize)]
struct Response {
evaluation_id: u64,
school: String,
question: String,
score: u8,
comment: Option<String>,
}
fn validate(row: &Response) -> Result<(), String> {
if !(1..=5).contains(&row.score) {
return Err(format!("score {} is outside 1 to 5", row.score));
}
if row.school.trim().is_empty() {
return Err(String::from("school is empty"));
}
if !row.question.starts_with('Q') {
return Err(format!("question '{}' is not like Q1", row.question));
}
Ok(())
}
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = csv::Reader::from_path("survey.csv")?;
let mut good: u64 = 0;
let mut bad: u64 = 0;
for (index, result) in reader.deserialize::<Response>().enumerate() {
let line = index + 2; // + 1 for counting from 1, + 1 for the header line
let checked = match result {
Ok(row) => validate(&row).map(|()| row),
Err(error) => Err(error.to_string()),
};
match checked {
Ok(row) => {
good += 1;
println!(
"#{} {} {}: {} {:?}",
row.evaluation_id, row.school, row.question, row.score, row.comment
);
}
Err(reason) => {
bad += 1;
eprintln!("skipped line {line}: {reason}");
}
}
}
eprintln!("{good} rows read, {bad} skipped");
Ok(())
}
#1001 Alexandria STEM Q1: 5 Some("Clear explanations")
#1001 Alexandria STEM Q2: 4 None
#1002 Cairo Language School Q1: 3 Some("Too fast")
#1003 Giza Primary Q2: 2 Some("Needs more examples, and a slower pace")
skipped line 5: CSV deserialize error: record 4 (line: 5, byte: 157): field 3: invalid digit found in string
skipped line 6: score 9 is outside 1 to 5
4 rows read, 2 skippedBoth kinds of failure become one Result<Response, String>, so they are reported the same way. validate(&row).map(|()| row) turns Ok(()) into Ok(row) and leaves an Err as it is.
The line number now comes from enumerate, plus 2. That is correct as long as no field contains a line break; the csv2json build takes it from the reader instead, which is always right.
5. Writing CSV
csv::Writer is the other direction, with Serialize. Writing goes through a buffer, so the last step is flush(): it pushes out what is left and reports a write error (a full disk, a closed pipe) that would otherwise be lost.
use std::error::Error;
use std::io;
use serde::Serialize;
#[derive(Serialize)]
struct SchoolScore {
school: String,
answers: u64,
average_tenths: u64,
}
fn main() -> Result<(), Box<dyn Error>> {
let rows = [
SchoolScore {
school: String::from("Alexandria STEM"),
answers: 2,
average_tenths: 45,
},
SchoolScore {
school: String::from("Giza Primary, east campus"),
answers: 1,
average_tenths: 20,
},
];
let mut writer = csv::Writer::from_writer(io::stdout());
for row in &rows {
writer.serialize(row)?;
}
writer.flush()?;
Ok(())
}
school,answers,average_tenths
Alexandria STEM,2,45
"Giza Primary, east campus",1,20The header line came from the field names, and the school with a comma in its name was quoted automatically. from_writer(io::stdout()) writes to the terminal; Writer::from_path("scores.csv") writes to a file.
Averages are kept in tenths (45 means 4.5), the same rule as money in cents: integers until the very end.
6. Real-world exports: semicolons and spaces
Excel in many European and Arabic locales saves CSV with ; between fields, and hand-edited files have spaces around values. ReaderBuilder configures the reader before opening the file:
use std::error::Error;
use csv::{ReaderBuilder, Trim};
use serde::Deserialize;
#[derive(Deserialize)]
struct Response {
evaluation_id: u64,
school: String,
question: String,
score: u8,
comment: Option<String>,
}
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = ReaderBuilder::new()
.delimiter(b';')
.trim(Trim::All)
.from_path("export.csv")?;
for result in reader.deserialize() {
let row: Response = result?;
println!(
"#{} {} {}: {} {:?}",
row.evaluation_id, row.school, row.question, row.score, row.comment
);
}
Ok(())
}
#1001 Alexandria STEM Q1: 5 Some("Clear explanations")
#1002 Cairo Language School Q1: 3 Noneb';' is a byte literal: one ASCII character as a u8, which is what the delimiter is. Trim::All trims headers and fields, so score still matches the score field.
Coming from PHP
The PHP version reads row by row too, and every value is a string:
<?php
$file = fopen('survey.csv', 'r');
$headers = fgetcsv($file);
while (($fields = fgetcsv($file)) !== false) {
$row = array_combine($headers, $fields); // fails if a row has a different number of fields
$score = (int) $row['score']; // "five" silently becomes 0
}
The memory behaviour is the same as Rust’s: one row at a time. The difference is in what reaches your code. (int) "five" is a valid score of 0 in PHP; in Rust the row is an Err with its line number, and you decide in one place what happens to bad rows.
PracticeThe csv tutorial, and an average per school
Skim the csv crate tutorial, sections “Reading CSV” and “Writing CSV”.
Exercise: average score per school
Read survey.csv, skip and report bad rows as in section 4, and write a CSV to stdout with one row per school: school,answers,average_tenths, sorted by school. Keep a BTreeMap<String, (u64, u64)> of (answers, sum of scores), then compute sum * 10 / answers for each.
Show the solution
use std::collections::BTreeMap;
use std::error::Error;
use std::io;
use serde::{Deserialize, Serialize};
#[derive(Deserialize)]
struct Response {
school: String,
score: u8,
}
#[derive(Serialize)]
struct SchoolScore {
school: String,
answers: u64,
average_tenths: u64,
}
fn main() -> Result<(), Box<dyn Error>> {
let mut reader = csv::Reader::from_path("survey.csv")?;
let mut totals: BTreeMap<String, (u64, u64)> = BTreeMap::new();
for (index, result) in reader.deserialize::<Response>().enumerate() {
match result {
Ok(row) if (1..=5).contains(&row.score) => {
let entry = totals.entry(row.school).or_insert((0, 0));
entry.0 += 1;
entry.1 += u64::from(row.score);
}
Ok(row) => eprintln!(
"skipped line {}: score {} is outside 1 to 5",
index + 2,
row.score
),
Err(error) => eprintln!("skipped line {}: {error}", index + 2),
}
}
let mut writer = csv::Writer::from_writer(io::stdout());
for (school, (answers, sum)) in totals {
writer.serialize(SchoolScore {
school,
answers,
average_tenths: sum * 10 / answers,
})?;
}
writer.flush()?;
Ok(())
}
school,answers,average_tenths
Alexandria STEM,2,45
Cairo Language School,1,30
Giza Primary,1,20
skipped line 5: CSV deserialize error: record 4 (line: 5, byte: 157): field 3: invalid digit found in string
skipped line 6: score 9 is outside 1 to 5The struct only lists the two columns it needs; the other columns are ignored, as with JSON. Ok(row) if … is a match guard: the arm applies only when the condition also holds, and the next arm catches the rest.
answers can never be 0 in the division: a school only enters the map with its first answer.
Remember
- Stream CSV row by row with
deserialize(), and decide on purpose: reject the batch or report each bad row and continue. - Report bad rows on stderr with their line numbers, and always say how many were skipped.
Tomorrow: rayon, and how changing iter() to par_iter() puts every core to work.