docs] to write data to a CSV file. Below is a example that shows you how you can write a slice of user-data related strings to a CSV file.

The code creates a new file called users.csv and writes a slice of records to it. Finally, the Flush method is used to flush any buffered data to the underlying io.Writer, which is the file.

">

How to Write Data to CSV in Go (original) (raw)

Written byEdd Turtle on gophercoding.com
on 11th of February 2023

(Updated: 2nd of April 2023)

In Go, you can use the standard library package encoding/csv [docs] to write data to a CSV file. Below is a example that shows you how you can write a slice of user-data related strings to a CSV file.

The code creates a new file called users.csv and writes a slice of records to it. Finally, the Flush method is used to flush any buffered data to the underlying io.Writer, which is the file.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 package main import ( "encoding/csv" "os" "fmt" ) func main() { // Define the data records := [][]string{ {"John", "Doe", "35"}, {"Jane", "Doe", "29"}, {"Jim", "Smith", "41"}, } filename := "users.csv" // Write it to CSV err := WriteToCsv(records, filename) if err != nil { panic(err) } fmt.Println("Created file:", filename) } // WriteToCsv accepts a slice of strings to write to a csv file. func WriteToCsv(records [][]string, filename string) error { file, err := os.Create(filename) if err != nil { return err } defer file.Close() writer := csv.NewWriter(file) defer writer.Flush() for _, record := range records { err := writer.Write(record) if err != nil { return err } } return nil }

Running this code should output the name of the file it’s just created. In our example, we also check for errors, but we just use a panic() - you are going to want to improve on this by handling the error appropriately.

Example In Action

golang write to csv

Author Edd Turtle

Edd is a PHP and Go developer who enjoys blogging about his experiences, mostly about creating and coding new things he's working on and is a big beliver in open-source and Linux.

Tweet me!☕ Buy me a Coffee