Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
58
Task/CSV-data-manipulation/Go/csv-data-manipulation.go
Normal file
58
Task/CSV-data-manipulation/Go/csv-data-manipulation.go
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
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)
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue