To encode and decode data in CSV format in Go, you can use the encoding/csv
package provided by the Go standard library. Here's an example:
import (
"encoding/csv"
"os"
)
// Create a new file to write the CSV data
file, err := os.Create("data.csv")
if err != nil {
panic(err)
}
defer file.Close()
// Create a CSV writer
writer := csv.NewWriter(file)
// Write header row
header := []string{"Name", "Age"}
writer.Write(header)
// Write data rows
data := [][]string{
{"John", "25"},
{"Alice", "30"},
{"Bob", "35"},
}
writer.WriteAll(data)
// Flush any buffered data to the underlying writer (file)
writer.Flush()
if err := writer.Error(); err != nil {
panic(err)
}
// Open the CSV file
file, err := os.Open("data.csv")
if err != nil {
panic(err)
}
defer file.Close()
// Create a CSV reader
reader := csv.NewReader(file)
// Read all records
records, err := reader.ReadAll()
if err != nil {
panic(err)
}
// Access the individual fields in each record
for _, record := range records {
name := record[0]
age := record[1]
// Process the data as needed
fmt.Println(name, age)
}
In the above example, the Write
method is used to write individual rows of data, and the WriteAll
method is used to write multiple rows at once. The Flush
method is necessary to ensure all data is written to the file. The ReadAll
method of the csv.Reader
reads all records from the CSV file, and you can iterate over them to access the individual fields.