write to a csv file in go

To write to a CSV file in Go, we can use the encoding/csv package. Here's an example of how to do it:

main.go
import (
    "encoding/csv"
    "bufio"
    "os"
)

func writeCSV(filename string, data [][]string) error {
    file, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer file.Close()

    writer := csv.NewWriter(bufio.NewWriter(file))
    defer writer.Flush()

    for _, row := range data {
        err := writer.Write(row)
        if err != nil {
            return err
        }
    }

    return nil
}
436 chars
26 lines

In this example, the writeCSV function takes a filename string and a 2D string slice data as parameters. The filename parameter specifies the output CSV file name, while data represents the data that we want to write to the file.

Inside the function, we first create a file object using the os.Create function. We check for errors and defer the file.Close() function call to make sure that the file is closed after we're done writing to it.

Next, we create a CSV writer object using csv.NewWriter, passing it a buffer created with bufio.NewWriter. We also defer writer.Flush() to make sure that any remaining CSV output is flushed to the file before we close it.

Finally, we loop through the rows in data and write each row to the CSV file using writer.Write. The Write function returns an error if something went wrong, so we check for and return any errors encountered in the process.

Here's an example of how to use the writeCSV function:

main.go
func main() {
    data := [][]string{
        {"John", "Doe", "john.doe@example.com"},
        {"Jane", "Doe", "jane.doe@example.com"},
        {"Bob", "Smith", "bob.smith@example.com"},
    }

    if err := writeCSV("output.csv", data); err != nil {
        panic(err)
    }
}
278 chars
12 lines

In this example, we create a 2D string slice named data containing some sample data, then call writeCSV and pass it the output filename and data slice as parameters. If an error occurs while writing to the output file, we panic and print the error message.

gistlibby LogSnag