Lesson 55 of 60 · Go
Reading & Writing CSV Files
Duration: 10 minutes
CSV Helpers
This lesson explains the main concept clearly with beginner-friendly examples and background so you can learn why the code works.
import (
"encoding/csv"
"os"
)
func writeCSV(path string, records [][]string) error {
f, err := os.Create(path)
if err != nil { return err }
defer f.Close()
w := csv.NewWriter(f)
defer w.Flush()
return w.WriteAll(records) // writes all rows
}
func readCSV(path string) ([][]string, error) {
f, err := os.Open(path)
if err != nil { return nil, err }
defer f.Close()
r := csv.NewReader(f)
return r.ReadAll()
}
Example usage
rows := [][]string{{"id","name"},{"1","Alice"}}
writeCSV("out.csv", rows)