pub struct Reader<R> { /* private fields */ }Expand description
Reads CSV data, either from a byte slice ([from_bytes]) or from any
std::io::Read source ([from_reader], requires std feature).
Rows are yielded by calling rows, which returns an iterator
of Row<'_>. Errors are deferred to the Row methods.
§Example
use csv::Reader;
use std::fs::File;
let mut reader = Reader::from_reader(File::open("data.csv")?);
for row in reader.rows() {
for field in row.fields()? {
}
}§Headers
Use parse_headers to read the first row as column headers.
Implementations§
Source§impl<R> Reader<R>
impl<R> Reader<R>
Sourcepub fn set_delimiter(&mut self, byte: u8) -> &mut Self
pub fn set_delimiter(&mut self, byte: u8) -> &mut Self
Set the field delimiter byte (default is ,).
Sourcepub fn set_headers(&mut self, headers: Vec<String>) -> &mut Self
pub fn set_headers(&mut self, headers: Vec<String>) -> &mut Self
Set column headers manually.
Use this when the CSV file has no header row but you still want
Row::deserialize to map struct fields by column name.
Must be called before iterating with rows.
use csv::Reader;
let mut reader = Reader::from_reader(std::io::Cursor::new(b"Alice,30\nBob,25\n"));
reader.set_headers(vec!["name".into(), "age".into()]);
for row in reader.rows() {
// row.deserialize::<MyStruct>() will match name/age by header
}Sourcepub fn headers(&self) -> Option<&[String]>
pub fn headers(&self) -> Option<&[String]>
Return the column headers, if parse_headers or set_headers was called.
Source§impl<R: Read> Reader<R>
impl<R: Read> Reader<R>
Sourcepub fn from_reader(source: R) -> Self
pub fn from_reader(source: R) -> Self
Create a reader from any std::io::Read source.
Data is streamed in chunks as rows are parsed, without loading the entire input into memory.
Sourcepub fn parse_headers(&mut self) -> Result<Vec<String>, ReadError>
pub fn parse_headers(&mut self) -> Result<Vec<String>, ReadError>
Read and return the first row as column headers.
If the CSV has no header row, use set_headers instead.
Source§impl<'a> Reader<&'a [u8]>
impl<'a> Reader<&'a [u8]>
Sourcepub fn from_bytes(bytes: &'a [u8]) -> Self
pub fn from_bytes(bytes: &'a [u8]) -> Self
Create a reader from a byte slice for in-memory parsing.
Unlike [from_reader], this does not require std and copies the
input into an internal buffer eagerly.
use csv::Reader;
let mut reader = Reader::from_bytes(b"a,b\n1,2\n");
let fields: Vec<Vec<String>> = reader.rows().map(|r| r.all().unwrap()).collect();
assert_eq!(fields, vec![vec!["a".to_string(), "b".to_string()], vec!["1".to_string(), "2".to_string()]]);