CSV File StringRecord

Hi,
I encountered a problem to parse a CSV file
As I am new to Rust, I don't know what to after getting a StringRecord from a line of my cvsfile and put it into a Struct

Didier

struct Protocol {
    id: i32,
    protocol_number: String,
    description: String,
    prefix: String,
    in_progress: bool,
    validity_date : String,
    expiration_date : String,
    customer_base : bool,
    contract_provision_file : String,
    guarranty : String,
    other_document : String,
    alert_message : String

}


pub fn example()  {
   
    let  _rdr = match ReaderBuilder::new()
        .has_headers(false)
        .delimiter(b';')
        
        .from_path("myapp_protocol.csv"){
 
        Ok( mut _rdr) => {
            for result in _rdr.records()
            {
                match  result {
                    Ok (r) => {
                        //let record = &r;
                        println!("record {:?} len {}", &r,&r.len());
                        
                        println!("", )
                    }
                    Err (e) => {
                        println!("{:?}", e);

                    }
                }
            }
                
                
        }
        Err(e) => {
                    // Il y a eu un problème, affichons l'erreur pour voir ce qu'il se passe
                    println!("{}", e);
            }
        };
    
}

You probably shouldn't be using records() if you want automatic deserialization with Serde. The docs contain a cookbook with examples for you: csv::cookbook - Rust

1 Like

Thanks !!
My problem is to read a csv file and I cannot deserialize if I change from std::io to from_file
It is difficult for me to understand which method I can use
Every example are given from a std::io not from a file

In the example from that cookbook chapter, you can replace this line:

    let mut rdr = csv::Reader::from_reader(io::stdin());

with this:

    let rdr = csv::ReaderBuilder::new()
        .has_headers(false)
        .delimiter(b';')
        .from_path("myapp_protocol.csv")?;

(Note the ? for handling filesystem errors.)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.