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()
}
Most Helpful This Week
Different ways for Integer to String Conversions
Interface embedding and calling interface methods from another package in Go (Golang)
Golang program for implementation of Huffman Coding Algorithm
Golang program for implementation of ZigZag Matrix
How do you send an HTTP GET request with an HTTP client in Go?
Program in Go language to Calculate Average Using Arrays