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
+15.8k Golang : Set up source IP address before making HTTP request
+19.6k Golang : Saving private and public key to files
+6.8k SSL : How to check if current certificate is sha1 or sha2 from command line
+14.3k Golang : How do I get the local IP (non-loopback) address ?
+20.1k Curl usage examples with Golang
+6.1k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+8.2k Golang : Go as a script or running go with shebang/hashbang style
+9.4k Golang : Convert file unix timestamp to UTC time example
+4.8k Python : Print unicode escape characters and string
+5.5k Golang : How to get capacity of a slice or array?
+10.2k Golang : Calculate Relative Strength Index(RSI) example
+5.6k Golang : Experimental emojis or emoticons icons programming language