commit | a96223109578917ed33c87bc4c7eee1b940a4aae | [log] [tgz] |
---|---|---|
author | android-build-team Robot <android-build-team-robot@google.com> | Wed Mar 24 03:04:19 2021 +0000 |
committer | android-build-team Robot <android-build-team-robot@google.com> | Wed Mar 24 03:04:19 2021 +0000 |
tree | b5728ec1db608d23cc8a6079ee964518bdf66da3 | |
parent | 61b36b156cc17cb77297a5e62df5b2f54062241a [diff] | |
parent | 543266151e1e216ccc43b511ca7615a3e6b0d8ca [diff] |
Snap for 7230858 from 543266151e1e216ccc43b511ca7615a3e6b0d8ca to tm-release Change-Id: I808411c4a051b15dda42cd2abaf97d47764d80e7
A fast and flexible CSV reader and writer for Rust, with support for Serde.
Dual-licensed under MIT or the UNLICENSE.
If you're new to Rust, the tutorial is a good place to start.
Add this to your Cargo.toml
:
[dependencies] csv = "1.1"
This example shows how to read CSV data from stdin and print each record to stdout.
There are more examples in the cookbook.
use std::error::Error; use std::io; use std::process; fn example() -> Result<(), Box<dyn Error>> { // Build the CSV reader and iterate over each record. let mut rdr = csv::Reader::from_reader(io::stdin()); for result in rdr.records() { // The iterator yields Result<StringRecord, Error>, so we check the // error here. let record = result?; println!("{:?}", record); } Ok(()) } fn main() { if let Err(err) = example() { println!("error running example: {}", err); process::exit(1); } }
The above example can be run like so:
$ git clone git://github.com/BurntSushi/rust-csv $ cd rust-csv $ cargo run --example cookbook-read-basic < examples/data/smallpop.csv
This example shows how to read CSV data from stdin into your own custom struct. By default, the member names of the struct are matched with the values in the header record of your CSV data.
use std::error::Error; use std::io; use std::process; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Record { city: String, region: String, country: String, population: Option<u64>, } fn example() -> Result<(), Box<dyn Error>> { let mut rdr = csv::Reader::from_reader(io::stdin()); for result in rdr.deserialize() { // Notice that we need to provide a type hint for automatic // deserialization. let record: Record = result?; println!("{:?}", record); } Ok(()) } fn main() { if let Err(err) = example() { println!("error running example: {}", err); process::exit(1); } }
The above example can be run like so:
$ git clone git://github.com/BurntSushi/rust-csv $ cd rust-csv $ cargo run --example cookbook-read-serde < examples/data/smallpop.csv