Home > Software design >  Rust Read CSV without header
Rust Read CSV without header

Time:03-26

How does one read a CSV without a header in Rust? I've searched through the docs and gone through like 15 examples each of which is subtly not what I'm looking for.

Consider how easy Python makes it:

csv.DictReader(f, fieldnames=['city']) 

How do you do this in Rust?

Current attempt:

use std::fs::File;
use serde::Deserialize;

#[derive(Debug, Deserialize)]
struct CityRow {
    city: &str,
    pop: u32,
}

fn doit() -> zip::result::ZipResult<()>
{
    let filename = "cities.csv";
    let mut zip = zip::ZipArchive::new(File::open(filename).unwrap())?;
    let mut file = zip.by_index(0).unwrap();
    println!("Filename: {}", file.name());
    let mut reader = csv::Reader::from_reader(Box::new(file));
    reader.set_headers(csv::StringRecord([  "city", "pop" ]));

    for record in reader.records() {
        // let record: CityRow = record.unwrap();
        // let record = record?;
        println!("{:?}", record);
    }

    Ok(())
}

CodePudding user response:

Use a ReaderBuilder, and call ReaderBuilder::has_headers to disable header parsing. You can then use StringRecord::deserialize to extract and print each record, skipping the first header row:

let mut reader = csv::ReaderBuilder::new()
    .has_headers(false)
    .from_reader(Box::new(file));

let headers = csv::StringRecord::from(vec!["city", "pop"]);
for record in reader.records().skip(1) {
    let record: CityRow = record.unwrap().deserialize(Some(&headers)).unwrap();
    println!("{:?}", record);
}

(playground)

  • Related