In last article, I wrote how to read CSV file content, split fields from line, etc.
Instead of reading and processing CSV file manually, Rust has a csv
crate can help us.
Let's bring back to our examresult.csv
:
Alice, 90
Bob, 85
Chris, 92
Delan, 88
The goal is the same: we read the content, get the second column to calculate the total score and average score.
Let's create a project cargo new csvreader
Then add csv
crate to the dependencies section:
[dependencies]
csv = "1.1"
Now let's code our main.rs
:
fn read_csv() {
let mut reader = csv::ReaderBuilder::new()
.has_headers(false)
.from_path("examresult.csv")
.expect("Cannot read fild");
let mut total_score = 0;
let mut total_count = 0;
for record in reader.records() {
total_score += record.unwrap()[1].trim().parse::<i32>().unwrap();
total_count += 1;
}
println!("Total score: {} Avg score: {}",
total_score,
(total_score as f32) / (total_count as f32));
}
fn main() {
read_csv();
}
First we create a csv reader from the crate ReaderBuilder
function and tell reader our CSV file doesn't have a header, such that our reader will not skip the first line.
Then we iterate reader.records()
, record is a type of Result, and the unwrap type is csv::string_record::StringRecord
, which we can index field by number like array or vector.
Run the code cargo run
, we got:
Total score: 355 Avg score: 88.75
Click to see more information about the csv crate.
Top comments (0)