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
+24.2k Golang : Convert uint value to string type
+6.7k Golang : Convert source code to assembly language
+13.1k Golang : concatenate(combine) strings
+5k Get website traffic ranking with Similar Web or Alexa
+12.3k Golang : Qt progress dialog example
+4.2k Golang : Customize scanner.Scanner to treat dash as part of identifier
+8.3k Golang : How to check if a string with spaces in between is numeric?
+28.9k Golang : How to get HTTP request header information?
+18.3k Golang : Get current URL example
+5k Golang : Use NLP to get sentences for each paragraph example
+5.1k Unix/Linux : How to open tar.gz file ?
+4.1k Golang : A program that contain another program and executes it during run-time