Converting an output (println!) to .csv file

Viewed 189
use yahoo_finance::{history, Interval, Timestamped};

#[tokio::main]

async fn main() {

    let data = history::retrieve_interval("AAPL", Interval::_6mo).await.unwrap();

    for end in &data {

        println!("Close ${:.2}, {}", end.close,end.datetime().format("%b %e %y)"));
    }
}

Basically, I want to take this program, and have the output as .csv file, not println!(), I just used println! to make sure the program worked. I'm still fairly new to Rust, and programming in general (apologies if I sound uneducated). I'm just making this program as something practical I can use (working in the finance industry) and build upon it.

2 Answers

You can do exactly that by using the writeln! macro instead of println!. You will need something that implements the Write trait, for example a File. This needs to be passed as the first argument to writeln!.

Your example would then be written like this:

use yahoo_finance::{history, Interval, Timestamped};

#[tokio::main]
async fn main() {
    let data = history::retrieve_interval("AAPL", Interval::_6mo).await.unwrap();

    // create a file called data.csv, overwriting the file if it already existed
    let mut file = std::fs::File::create("data.csv");

    for end in &data {
        // write to the file instead of standard output
        writeln!(file, "Close ${:.2}, {}", end.close,end.datetime().format("%b %e %y"));
    }
}

I removed the parenthesis in the date format, I think that was by mistake? Anyway I hope I could help.

As others have noted, this is not the cleanest solution possible and you might have to pay attention to quoting things yourself and such, so looking into using a CSV library might also be a good idea. But in this case I think it should work fine like this.

There is a std::fs::File API which lets you create files. On these files, there is a write function into which you can pass in String. There is a format! macro that lets you do the same thing as println! but it returns a String instead. So if you piece this all together, you should be able to create a file with a name ending in .csv and then use the API to write stuff to it in a for loop like you did with println!.

Probably a more appropriate way to do this though is to look up a csv crate that can give you some more csv specific functionality. A quick search came up with this library.

Related