Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Day3 - CSV - Writer::from_file() deprecated #18

Open
Sefrys opened this issue Dec 17, 2019 · 1 comment
Open

Day3 - CSV - Writer::from_file() deprecated #18

Sefrys opened this issue Dec 17, 2019 · 1 comment

Comments

@Sefrys
Copy link

Sefrys commented Dec 17, 2019

The method from_file() for Writer from BurntSushi's CSV crate has been deprecated a while ago and replaced by from_path(). As a relatively new person to Rust, this kind of got me stuck with the presented examples for writing into a CSV file until I dug into the documentation :).

Instead of:

let dollar_films = vec![
    ("A Fistful of Dollars", "Rojo", 1964),
    ("For a Few Dollars More", "El Indio", 1965),
    ("The Good, the Bad and the Ugly", "Tuco", 1966),
];
let path = "westerns.csv";
let mut writer = Writer::from_file(path).unwrap();
for row in dollar_films {
    writer.encode(row).expect("CSV writer error");
}

The following works just fine using the current version of CSV crate (1.1.1):

let dollar_films = vec![
    ["A Fistful of Dollars", "Rojo", "1964"],
    ["For a Few Dollars More", "El Indio", "1965"],
    ["The Good, the Bad and the Ugly", "Tuco", "1966"],
];
let path = "westerns.cvs";
let mut writer = Writer::from_path(path).unwrap();
for row in dollar_films {
    writer.write_record(&row).expect("CSV writer error");
    writer.flush();
}
@nitzel
Copy link

nitzel commented Sep 29, 2020

For others being stuck here, as of CSV v 1.1.3
writer.encode(row)
has changed to
writer.serialize(row)
as well.

Then you can keep the type of dollay_films a Vec<(&str, &str, i32)> instead of changing it to Vec<[&str; _]> by storing the years as strings instead of numbers.


Also, to be able to serialize Movie with csv:

in Cargo.toml, add dependency serde = { version = "1.0", features = ["derive"] }
and then in day3.rs

use serde::{Serialize, Deserialize};

#[derive(Serialize, Deserialize, Debug)] // Debug to be able to print movies
struct Movie { // ..

To skip the csv headers one now needs to configure the reader via:

  let mut rb = ReaderBuilder::new();
  rb.has_headers(false);

  let mut reader = rb.from_path(path).unwrap();

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants