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
+31.8k Golang : Upload and download file to/from AWS S3
+12.2k Golang : Submit web forms without browser by http.PostForm example
+7k Golang : automatically figure out array length(size) with three dots
+30.6k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+10.1k Swift : Convert (cast) Int or int32 value to CGFloat
+24.8k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+33k Golang : Read a text file and replace certain words
+3.5k PHP : Extract part of a string starting from the middle
+37.5k Golang : Convert []byte to image
+6.5k Golang : Check if integer is power of four example
+10.2k Golang : Get absolute path to binary for os.Exec function with exec.LookPath
+24.2k Golang : Encrypt and decrypt data with AES crypto