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..
")
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.