working with csv files in golang code example

Example 1: golang read csv file

package main

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

func readCsvFile(filePath string) [][]string {
    f, err := os.Open(filePath)
    if err != nil {
        log.Fatal("Unable to read input file " + filePath, err)
    }
    defer f.Close()

    csvReader := csv.NewReader(f)
    records, err := csvReader.ReadAll()
    if err != nil {
        log.Fatal("Unable to parse file as CSV for " + filePath, err)
    }

    return records
}

func main() {
    records := readCsvFile("../tasks.csv")
    fmt.Println(records)
}

Example 2: how to create csv file in golang

package main

import (
	"encoding/csv"
	"log"
	"os"
)

func main() {
	empData := [][]string{
		{"Name", "City"},
		{"Smith", "India"},
	}
    
	csvFile, err := os.Create("fileName.csv")

	if err != nil {
		log.Fatalf("failed creating file: %s", err)
	}

	csvwriter := csv.NewWriter(csvFile)

	for _, empRow := range empData {
		_ = csvwriter.Write(empRow)
	}
	csvwriter.Flush()
	csvFile.Close()
}

Tags:

Misc Example