append to a csv file in rust

To append to an existing CSV file in Rust, we first need to open the file in append mode using the OpenOptions struct from the std::fs module. We then initialize a CSV writer with the from_writer method from the csv::Writer struct. We can then write a new row using the write_record method on the CSV writer.

Here's an example implementation:

main.rs
use std::fs::OpenOptions;
use csv::Writer;

fn append_to_csv(file_path: &str, row: &[&str]) -> Result<(), csv::Error> {
    let mut file = OpenOptions::new()
        .write(true)
        .create(true)
        .append(true)
        .open(file_path)?;

    let mut writer = Writer::from_writer(file);
    writer.write_record(row)?;

    writer.flush()?;
    Ok(())
}
365 chars
17 lines

In this implementation, append_to_csv takes in the path to the CSV file as a string, and the row to be added as a slice of string references. The ? operator at the end of the function calls is used to propagate any errors that occur during file opening or writing.

We first create a OpenOptions instance and set the write, create, and append options to true. The open method returns a Result<File> instance which we then unwrap into a mutable file.

We then create a Writer instance from the file by passing it to the from_writer method. We can then use the write_record method to write the row passed to the function.

Finally, we call flush method to force any remaining contents to be written to the file and return Ok(()) to indicate a successful write.

related categories

gistlibby LogSnag