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
+19.5k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+7.5k Golang : get the current working directory of a running program
+5.2k Golang : Display advertisement images or strings on random order
+6k Golang : How to search a list of records or data structures
+5.2k How to check with curl if my website or the asset is gzipped ?
+10.9k Golang : Proper way to test CIDR membership of an IP 4 or 6 address example
+4.8k Golang : Constant and variable names in native language
+5.8k Golang : How to verify input is rune?
+5.1k Python : Delay with time.sleep() function example
+7.2k Golang : Rot13 and Rot5 algorithms example
+13.9k Golang : Check if a file exist or not