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