create a csv file in go

To create a CSV file in Go, we can make use of the encoding/csv package which provides functionality for reading and writing CSV files.

Here's a sample code snippet that creates a CSV file with some data:

main.go
package main

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

func main() {
    // create the file
    file, err := os.Create("data.csv")
    if err != nil {
        log.Fatal("Cannot create file", err)
    }
    defer file.Close()

    // define the data
    data := [][]string{
        {"Name", "Age", "City"},
        {"John Doe", "32", "New York"},
        {"Jane Smith", "27", "San Francisco"},
        {"Bob Johnson", "45", "Chicago"},
    }

    // create a new CSV writer
    writer := csv.NewWriter(file)

    // write the data to the file
    for _, record := range data {
        err := writer.Write(record)
        if err != nil {
            log.Fatal("Error writing record to file", err)
        }
    }

    // flush the writer
    writer.Flush()

    log.Println("CSV file created successfully.")
}
817 chars
41 lines

This code will create a file named data.csv in the current directory and write the CSV data to it.

related categories

gistlibby LogSnag