To read and write data using the encoding/csv
package in Go, you need to follow these steps:
encoding/csv
package.import (
"encoding/csv"
"os"
)
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)
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)
}
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)
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
}
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.