Skip to content

how do I write column oriented data to a CSV format? #340

Answered by BurntSushi
hanusek asked this question in Q&A
Discussion options

You must be logged in to vote

CSV data is written one row at a time. That's a fundamental fact about the CSV format and there is no way to change it. Thus, if your data is arranged by column and you need to format it as CSV data, then the only choice available to you is to convert your data such that it is arranged by row in some way.

Here's one somewhat simplistic example that will write a HashMap<String, Vec<i64>> as CSV data:

use std::collections::HashMap;

fn main() -> anyhow::Result<()> {
    let mut data = HashMap::new();
    data.insert("field1".to_string(), vec![1, 2, 3, 4, 5]);
    data.insert("field2".to_string(), vec![10, 20, 30, 40, 50]);
    data.insert("field3".to_string(), vec![100, 200, 300, 400, 500]);

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by hanusek
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #339 on October 04, 2023 11:17.