Read CSV file as a vector of StringRecords
-
StringRecord
-
We read the rows (skipping the first row)
-
We can iterate over the rows or access the individual elements
Planet name,Distance (AU),Mass
Mercury,0.4,0.055
Venus,0.7,0.815
Earth,1,1
Mars,1.5,0.107
Ceres,2.77,0.00015
Jupiter,5.2,318
Saturn,9.5,95
Uranus,19.6,14
Neptune,30,17
Pluto,39,0.00218
Charon,39,0.000254
[package]
name = "handle-csv"
version = "0.1.0"
edition = "2024"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
csv = "1.2.2"
use std::fs::File;
fn main() {
let filepath = "planets.csv";
let rows = read_file(filepath);
for row in &rows {
println!("{:?}", row);
println!("{}", &row[0]);
}
println!("------");
for value in &rows[0] {
println!("{}", value);
}
println!("------");
println!("{}", &rows[3][0]);
}
fn read_file(filepath: &str) -> Vec<csv::StringRecord> {
let mut rows: Vec<csv::StringRecord> = vec![];
match File::open(filepath) {
Ok(file) => {
let mut rdr = csv::Reader::from_reader(file);
for result in rdr.records() {
match result {
Ok(row) => {
rows.push(row.clone());
}
Err(err) => panic!("Error {}", err),
};
}
}
Err(error) => panic!("Error opening file {}: {}", filepath, error),
}
rows
}
StringRecord(["Mercury", "0.4", "0.055"])
Mercury
StringRecord(["Venus", "0.7", "0.815"])
Venus
StringRecord(["Earth", "1", "1"])
Earth
StringRecord(["Mars", "1.5", "0.107"])
Mars
StringRecord(["Ceres", "2.77", "0.00015"])
Ceres
StringRecord(["Jupiter", "5.2", "318"])
Jupiter
StringRecord(["Saturn", "9.5", "95"])
Saturn
StringRecord(["Uranus", "19.6", "14"])
Uranus
StringRecord(["Neptune", "30", "17"])
Neptune
StringRecord(["Pluto", "39", "0.00218"])
Pluto
StringRecord(["Charon", "39", "0.000254"])
Charon
------
Mercury
0.4
0.055
------
Mars