Golang : How to write CSV data to file
This tutorial is a continuation from previous tutorial on reading CSV file. The code below will demonstrate how easy it is to write CSV data into a file.
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
csvfile, err := os.Create("output.csv")
if err != nil {
fmt.Println("Error:", err)
return
}
defer csvfile.Close()
records := [][]string{{"item1", "value1"}, {"item2", "value2"}, {"item3", "value3"}}
writer := csv.NewWriter(csvfile)
for _, record := range records {
err := writer.Write(record)
if err != nil {
fmt.Println("Error:", err)
return
}
}
writer.Flush()
}
Content from output.csv file
item1,value1
item2,value2
item3,value3
The code above write a single line of CSV data for each loop. To write all CSV data at once, please see WriteAll at
https://www.socketloop.com/references/golang-encoding-csv-writer-writeall-function-example
Reference :
https://www.socketloop.com/references/golang-encoding-csv-newwriter-function-example
See also : Golang : How to read CSV file
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+5.6k Golang : Spell checking with ispell example
+17.7k Golang : Delete duplicate items from a slice/array
+10.4k Golang : Secure file deletion with wipe example
+12.7k Golang : Fix cannot use buffer (type bytes.Buffer) as type io.Writer(Write method has pointer receiver) error
+9.8k Golang : Natural string sorting example
+3k Golang : PGX CopyFrom to insert rows into Postgres database
+8.9k Golang : Find and replace data in all files recursively
+8.2k Golang : does not implement flag.Value (missing Set method)
+7.9k Golang : Take screen shot of browser with JQuery example
+6k Golang : How to detect if a sentence ends with a punctuation?
+7.1k Golang : Oanda bot with Telegram and RSI example