I am quite new to rust, and am trying to use the csv and serde crates to read a .csv file.
The issue that I am having is that the csv file has some junk at the front, so I need trim that off before I can read the data that I want.
I do not get any compilation errors, but I do not get any prints from the csv deserialization block
I know that in my code, the data is ok up right until I make the csv reader.
use std::{
error::Error,
fs::File,
process,
env,
};
use std::io::{self,BufRead,BufReader,Read,Cursor};
use serde::Deserialize;
use csv::Trim;
#[derive(Debug, Deserialize)]
struct Record {
/* omitted due to length I am fairly certain the problem is not here */
}
fn run() -> Result<(), Box<dyn Error>> {
// Get the command-line arguments
let args: Vec<String> = env::args().collect();
println!("{:?}", args);
if args.len() != 2 {
eprintln!("Usage: {} <filename.csv>", args[0]);
process::exit(1);
}
let filename = &args[1];
// Open the CSV file
let file = File::open(filename)?;
let reader = io::BufReader::new(file);
// Create an iterator over the lines
let mut lines_iter = reader.lines();
// Skip the first 8 lines
for _ in 0..8 {
if let Some(line) = lines_iter.next() {
// Skip the line
} else {
// File has fewer than 8 lines, handle this error case if needed
eprintln!("File has fewer than 8 lines");
process::exit(1);
}
}
let mut remaining_lines = Vec::new();
// Collect the remaining lines, removing newline characters
for line in lines_iter {
let line = line?;
let trimmed_line = line.to_string(); // Convert &str to String
println!("{:?}", &trimmed_line); //testing statement
remaining_lines.push(trimmed_line);
}
let csv_data = remaining_lines.join(","); //problem here
// Create CSV reader from the remaining lines
let mut rdr = csv::ReaderBuilder::new()
// .trim(Trim::Fields)
.from_reader(Cursor::new(csv_data)); //or here
// Iterate over CSV records and process them
for result in rdr.deserialize() {
let record: Record = result?;
println!("{:?}", record);
}
Ok(())
}
fn main() {
if let Err(err) = run() {
println!("{}", err);
process::exit(1);
}
}
New contributor
lawdhalf is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.