append to a csv file in go

To append to a CSV file in Go, you can use the built-in csv and os packages to open the file in append mode and write to it.

Here's an example code block that demonstrates how to do this:

main.go
package main

import (
	"encoding/csv"
	"os"
)

func main() {
	// Open file in append mode
	file, err := os.OpenFile("myFile.csv", os.O_APPEND|os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	defer file.Close()

	// Create CSV writer
	writer := csv.NewWriter(file)

	// Write new row to file
	newRow := []string{"Value1", "Value2", "Value3"}
	err = writer.Write(newRow)
	if err != nil {
		panic(err)
	}

	// Flush all data to the file
	writer.Flush()
}
457 chars
29 lines

In this example, we first open the CSV file in append mode using os.OpenFile(). Then, we create a new csv.Writer for the file and write a new CSV row to it using the writer.Write() method.

Finally, we flush all data to the file using writer.Flush(). This ensures that all data is written to the file before the program exits.

related categories

gistlibby LogSnag