Golang write CSV records
The csv package have a
NewWriter()
function which returns a Writer
object which is used for writing CSV data. A csv.Writer
writes csv records which are terminated by a newline and uses a comma as the field delimiter. The following source code snippet shows how to write data to a CSV file.
Example
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
rows := [][]string{
{"Name", "City", "Language"},
{"Pinky", "London", "Python"},
{"Nicky", "Paris", "Golang"},
{"Micky", "Tokyo", "Php"},
}
csvfile, err := os.Create("test.csv")
if err != nil {
log.Fatalf("failed creating file: %s", err)
}
csvwriter := csv.NewWriter(csvfile)
for _, row := range rows {
_ = csvwriter.Write(row)
}
csvwriter.Flush()
csvfile.Close()
}