Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append slice to csv golang

Tags:

csv

go

I tried to create a simple function to append a slice value to the next column of a created csv file. The aim is to have this style in test.csv

|columnA |columnB|

|header1 |header2|

|FIRSTVALUE| SECONDVALUE |

(sorry for the bad formating, but once the text.csv is generated, if we open the text.csv file,the idea is to have the "SECONDVALUE" put in the next column after the "FIRSTVALUE" (as is depicted in the diagram above).. and everytime the function is called, it will keep appending the next value after the previous column in the same line).

This is how far I got, it is however appending the SECONDVALUE directly on the same column of FIRSTVALUE.. (so instead of getting "|FIRSTVALUE | SECONDVALUE" , I get "|FIRSTVALUESECONDVALUE|" )

package main

import (
    "encoding/csv"
    "fmt"
    "os"
    "strings"
)


func main() {
    callfunc()
}

func callfunc() int {

    testval1 := []string{"FIRST VALUE"}
    test(testval1, "test.csv", 1)

    testval2 := []string{"SECOND VALUE"}
    test(testval2, "test.csv", 0) //I want this to be added to the column next to first value 

    return 1
}


func test(lines []string, path string, header int) {

    var hdr = []string{"header1", "header2"}

    fmt.Println("inside the method..\n")

    file, err := os.OpenFile(path, os.O_APPEND|os.O_WRONLY, 0600)
    if err != nil {
        if file, err = os.Create(path); err != nil {
            return
        }
    }
    defer file.Close()

    writer := csv.NewWriter(file)

    if header == 1 {
        returnError := writer.Write(hdr)
        if returnError != nil {
            fmt.Println(returnError)
        }
    }

    writer.Flush()

    for _, value := range lines {
        _, err := file.WriteString(strings.TrimSpace(value))
        if err != nil { //exception handler
            fmt.Println(err)
            break
        }
    }

    writer.Flush()
}

how to fix the above line of code , so that "SECONDVALUE" is the second column, and not in the same column where the "FIRSTVALUE" is.

like image 893
sateayam Avatar asked Feb 14 '26 08:02

sateayam


2 Answers

func addcol(fname string, column []string)  {
 // read the file
 f, err := os.OpenFile(fname, os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
 if err != nil {
     fmt.Println("Error: ", err)
     return
 }
 w := csv.NewWriter(f)
 w.Write(column)
 w.Flush()
}

copy from https://www.reddit.com/r/golang/comments/46fdef/help_appending_a_slice_to_next_row_in_csv_file/

like image 183
Lewis Avatar answered Feb 17 '26 12:02

Lewis


Your code includes things which I couldn’t understand clearly, so here’s a tiny program that does what your are asking for. You can build on top of it.

package main

import (
    "encoding/csv"
    "os"
)

func addcol(fname string, column []string) error {
    // read the file
    f, err := os.Open(fname)
    if err != nil {
        return err
    }
    r := csv.NewReader(f)
    lines, err := r.ReadAll()
    if err != nil {
        return err
    }
    if err = f.Close(); err != nil {
        return err
    }

    // add column
    l := len(lines)
    if len(column) < l {
        l = len(column)
    }
    for i := 0; i < l; i++ {
        lines[i] = append(lines[i], column[i])
    }

    // write the file
    f, err = os.Create(fname)
    if err != nil {
        return err
    }
    w := csv.NewWriter(f)
    if err = w.WriteAll(lines); err != nil {
        f.Close()
        return err
    }
    return f.Close()
}

func main() {
    col := []string{"column two", "a", "b", "c", "d"}
    if err := addcol("in.csv", col); err != nil {
        panic(err)
    }
}
like image 25
Mostafa Avatar answered Feb 17 '26 12:02

Mostafa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!