Errorum
Errorum

Reputation: 223

Golang Write New Column of CSV

I'm writing out two sets of data to one CSV in Go. Right now, using csv.NewWriter, I can write them to the same columns. This is not ideal, I would like them side-by-side, the second dataset in adjacent columns. Here's what I'm doing now:

    csvOut, _ := os.Create("Summary.csv")
    writer := csv.NewWriter(csvOut)

    for _, value := range dataset1 {
            writer.Write(value)
    }
    writer.Flush()
    for _, value := range dataset2 {
            writer.Write(value)
    }
    writer.Flush()

I know the normal writer has some offset options, does the csv writer have anything similar?

Upvotes: 2

Views: 4414

Answers (2)

Shihe Zhang
Shihe Zhang

Reputation: 2771

Loop over the source data set records seem inevitable, but you could set the record ready and then use the WriteAll function.
That would lead to a different design, which takes [][]string as input, no matter how many data set are there.

heads := []string{"first_name", "last_name"}

dataSet1 := []string{"Tom", "Jack", "James"}
dataSet2 := []string{"Hanks", "Sparrow", "Blunt"}

var records [][]string
records = append(records, heads)
for i := range dataSet1 {
    record := []string{dataSet1[i], dataSet2[i]}
    records = append(records, record)
}

w := csv.NewWriter(os.Stdout)
w.WriteAll(records) // calls Flush internally

if err := w.Error(); err != nil {
    log.Fatalln("error writing csv:", err)
}

Output:

first_name,last_name
Tom,Hanks
Jack,Sparrow
James,Blunt

https://go.dev/play/p/snk_bsVDtwI

Upvotes: 2

Thundercat
Thundercat

Reputation: 120999

Loop over the source data set records. Concatenate the records from each data set to create an output record. Write the output record to the file.

csvOut, _ := os.Create("Summary.csv")
writer := csv.NewWriter(csvOut)

var record []string  // declare record outside loop to reduce allocations
for i := range dataset1 {
        record = append(record[:0], dataset1[i]...) // copy data set 1 to beginning of output record
        record = append(record, dataset2[i]...) // append data set 2 to output record
        writer.Write(record)
}
writer.Flush()

This code assumes that len(dataset1) == len(dataset2). If this is not true, then modify the code per application requirements (add empty values, truncate to shorter dataset, ...)

Upvotes: 4

Related Questions