How to read a csv file in Rust?

Member

by vivien , in category: Other , a year ago

How to read a csv file in Rust?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by anahi.murazik , a year ago

@vivien 

To read a CSV (Comma Separated Values) file in Rust, you can use a CSV parsing library such as csv or rust-csv.


Here's an example of how to use the csv crate to read a CSV file and print each record:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
extern crate csv;

use std::error::Error;
use std::fs::File;
use std::io::BufReader;

fn main() -> Result<(), Box<dyn Error>> {
    let file = File::open("input.csv")?;
    let reader = BufReader::new(file);

    let mut rdr = csv::Reader::from_reader(reader);
    for result in rdr.records() {
        let record = result?;
        println!("{:?}", record);
    }
    Ok(())
}


This example opens a file called input.csv, creates a CSV reader from it, and iterates over the records in the file, printing each record to the console.


Note that this example uses the ? operator to propagate errors up the call stack. If any step in the process of opening the file or reading from it fails, the error will be returned and the program will terminate.


For more information on reading CSV files in Rust, you can check out the documentation for the csv crate: https://docs.rs/csv/.

Member

by josh , 4 months ago

@vivien 

The provided code is correct. However, depending on the version of the csv crate you are using, the syntax may have changed slightly. Here is an updated example using the latest version of the csv crate (1.1.6 as of writing):

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
use std::error::Error;
use std::fs::File;
use std::io::BufReader;
use csv::ReaderBuilder;

fn main() -> Result<(), Box<dyn Error>> {
    let file = File::open("input.csv")?;
    let reader = BufReader::new(file);

    let mut rdr = ReaderBuilder::new().from_reader(reader);
    for result in rdr.records() {
        let record = result?;
        println!("{:?}", record);
    }
    Ok(())
}


To use the latest version of the csv crate, you need to include the corresponding dependency in your Cargo.toml file:

1
2
[dependencies]
csv = "1.1.6"


With this updated code, you should be able to successfully read and print the records from a CSV file using Rust.