[Go] Write records to a CSV file

Created on November 30, 2026

You can use encoding/csv to write rows to a file. Each inner slice in this example holds the fields for one row, including the header row.

package main

import (
    "encoding/csv"
    "log"
    "os"
)

func main() {
    records := [][]string{
        {"name", "age", "country"},
        {"Tanaka", "20", "Japan"},
        {"Bob", "25", "USA"},
        {"Tom", "30", "England"},
    }

    file, err := os.Create("output.csv")
    if err != nil {
        log.Fatal(err)
    }

    writeErr := csv.NewWriter(file).WriteAll(records)
    closeErr := file.Close()
    if writeErr != nil {
        log.Fatal(writeErr)
    }
    if closeErr != nil {
        log.Fatal(closeErr)
    }
}

os.Create opens output.csv for writing and truncates any existing file with that name. WriteAll writes the records and flushes the CSV writer.

The file contains:

name,age,country
Tanaka,20,Japan
Bob,25,USA
Tom,30,England
Go