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
+17.7k Golang : Clone with pointer and modify value
+4.9k Golang : How to pass data between controllers with JSON Web Token
+17.2k Golang : Covert map/slice/array to JSON or XML format
+21.4k Golang : Clean up null characters from input data
+18.6k Golang : Write file with io.WriteString
+7k Golang : Join lines with certain suffix symbol example
+23.3k Golang : Print out struct values in string format
+15k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+16.6k Golang : Send email and SMTP configuration example
+6.3k PHP : Get client IP address
+6.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+5.5k Golang : Return multiple values from function