How to read and write data using the encoding/csv package for CSV I/O in Go?

To read and write data using the encoding/csv package in Go, you need to follow these steps:

  1. Import the encoding/csv package.
import ( "encoding/csv" "os" )
  1. To read data from a CSV file, open the file using os.Open() and create a new csv.Reader using csv.NewReader(). Pass the opened file as an argument to NewReader().
file, err := os.Open("data.csv") if err != nil { // Handle error } defer file.Close() reader := csv.NewReader(file)
  1. Use the Read() method of the csv.Reader to read records from the CSV file. This method returns a slice of strings, where each element represents a field in a CSV record.
for { record, err := reader.Read() if err == io.EOF { break } if err != nil { // Handle error } // Process the record fmt.Println(record) }
  1. To write data to a CSV file, open the file using os.Create() or os.OpenFile() and create a new csv.Writer using csv.NewWriter(). Pass the opened file as an argument to NewWriter(). You can also specify a custom delimiter or other options when creating the writer.
file, err := os.Create("output.csv") if err != nil { // Handle error } defer file.Close() writer := csv.NewWriter(file)
  1. Use the Write() method of the csv.Writer to write records to the CSV file. The Write() method accepts a slice of strings, where each element represents a field in a CSV record.
record := []string{"John Smith", "43", "Engineer"} writer.Write(record) // Call Flush() to ensure the buffered data is written to the file writer.Flush() if err := writer.Error(); err != nil { // Handle error }
  1. You can also write multiple records at once using the WriteAll() method. Pass a slice of slices of strings to the WriteAll() method, where each inner slice represents a record.
records := [][]string{ {"John Smith", "43", "Engineer"}, {"Jane Doe", "37", "Manager"}, {"Alice Cooper", "28", "Developer"}, } writer.WriteAll(records) // Call Flush() to ensure the buffered data is written to the file writer.Flush() if err := writer.Error(); err != nil { // Handle error }

Remember to handle errors appropriately while reading or writing CSV files.