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
+35.1k Golang : Integer is between a range
+9.3k Golang : Extract or copy items from map based on value
+10.6k PHP : Convert(cast) bigInt to string
+36.1k Golang : Validate IP address
+7.6k Javascript : How to check a browser's Do Not Track status?
+41.2k Golang : How do I convert int to uint8?
+8.6k Golang : Get final balance from bit coin address example
+19.5k Golang : Measure http.Get() execution time
+6.2k Golang : Handling image beyond OpenCV video capture boundary
+78.3k Golang : How to return HTTP status code?
+9.4k Golang : How to generate Code 39 barcode?
+9.7k Golang : Convert octal value to string to deal with leading zero problem