1csv
2===
3A fast and flexible CSV reader and writer for Rust, with support for Serde.
4
5[![Build status](https://github.com/BurntSushi/rust-csv/workflows/ci/badge.svg)](https://github.com/BurntSushi/rust-csv/actions)
6[![crates.io](https://img.shields.io/crates/v/csv.svg)](https://crates.io/crates/csv)
7
8Dual-licensed under MIT or the [UNLICENSE](http://unlicense.org).
9
10
11### Documentation
12
13https://docs.rs/csv
14
15If you're new to Rust, the
16[tutorial](https://docs.rs/csv/1.*/csv/tutorial/index.html)
17is a good place to start.
18
19
20### Usage
21
22To bring this crate into your repository, either add `csv` to your
23`Cargo.toml`, or run `cargo add csv`.
24
25
26### Example
27
28This example shows how to read CSV data from stdin and print each record to
29stdout.
30
31There are more examples in the
32[cookbook](https://docs.rs/csv/1.*/csv/cookbook/index.html).
33
34```rust
35use std::{error::Error, io, process};
36
37fn example() -> Result<(), Box<dyn Error>> {
38    // Build the CSV reader and iterate over each record.
39    let mut rdr = csv::Reader::from_reader(io::stdin());
40    for result in rdr.records() {
41        // The iterator yields Result<StringRecord, Error>, so we check the
42        // error here.
43        let record = result?;
44        println!("{:?}", record);
45    }
46    Ok(())
47}
48
49fn main() {
50    if let Err(err) = example() {
51        println!("error running example: {}", err);
52        process::exit(1);
53    }
54}
55```
56
57The above example can be run like so:
58
59```text
60$ git clone git://github.com/BurntSushi/rust-csv
61$ cd rust-csv
62$ cargo run --example cookbook-read-basic < examples/data/smallpop.csv
63```
64
65### Example with Serde
66
67This example shows how to read CSV data from stdin into your own custom struct.
68By default, the member names of the struct are matched with the values in the
69header record of your CSV data.
70
71```rust
72use std::{error::Error, io, process};
73
74#[derive(Debug, serde::Deserialize)]
75struct Record {
76    city: String,
77    region: String,
78    country: String,
79    population: Option<u64>,
80}
81
82fn example() -> Result<(), Box<dyn Error>> {
83    let mut rdr = csv::Reader::from_reader(io::stdin());
84    for result in rdr.deserialize() {
85        // Notice that we need to provide a type hint for automatic
86        // deserialization.
87        let record: Record = result?;
88        println!("{:?}", record);
89    }
90    Ok(())
91}
92
93fn main() {
94    if let Err(err) = example() {
95        println!("error running example: {}", err);
96        process::exit(1);
97    }
98}
99```
100
101The above example can be run like so:
102
103```
104$ git clone git://github.com/BurntSushi/rust-csv
105$ cd rust-csv
106$ cargo run --example cookbook-read-serde < examples/data/smallpop.csv
107```
108