How to encode and decode data in CSV (Comma-Separated Values) format in Go?

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:

  1. Import the required packages:
import ( "encoding/csv" "os" )
  1. Encode data to CSV format:
// 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) }
  1. Decode data from CSV format:
// 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.