Golang Read Write and Process data in CSV
Sample csv should have sample data as shown below
Example
package main
import (
"encoding/csv"
"log"
"os"
"strconv"
)
func main() {
rows := readSample()
appendSum(rows)
writeChanges(rows)
}
func readSample() [][]string {
f, err := os.Open("sample.csv")
if err != nil {
log.Fatal(err)
}
rows, err := csv.NewReader(f).ReadAll()
f.Close()
if err != nil {
log.Fatal(err)
}
return rows
}
func appendSum(rows [][]string) {
rows[0] = append(rows[0], "SUM")
for i := 1; i < len(rows); i++ {
rows[i] = append(rows[i], sum(rows[i]))
}
}
func sum(row []string) string {
sum := 0
for _, s := range row {
x, err := strconv.Atoi(s)
if err != nil {
return "NA"
}
sum += x
}
return strconv.Itoa(sum)
}
func writeChanges(rows [][]string) {
f, err := os.Create("output.csv")
if err != nil {
log.Fatal(err)
}
err = csv.NewWriter(f).WriteAll(rows)
f.Close()
if err != nil {
log.Fatal(err)
}
}
Most Helpful This Week
How to kill execution of goroutine?
How to find out element position in slice?
How to reads and decodes JSON values from an input stream?
How to Unmarshal nested JSON structure?
Anonymous Functions in Golang
How to create Empty and Nil Slice?
Find length of Channel, Pointer, Slice, String and Map
How to import structs from another package in Go?
Get Year, Month, Day, Hour, Min and Second from current date and time.
How to import and alias package names?