Go csv.Reader.Read
encoding/csv understands quoted delimiters and returns one record per successful Read call. End of input is reported as io.EOF.
A simple example
csv.Reader.Read
- Start with CSV row containing A,2
- Do this Parse the two fields
- Result A and 2
Syntax
record, err := reader.Read()
Run this example in Go
Save the program as main.go. Use Go 1.21 or later.
go run main.go
Read quoted invoice fields from CSV
A supplier sends a CSV invoice whose quoted description contains a comma. Use a CSV reader that understands quoting so the amount stays in its proper column and the description remains intact.
package main
import (
"encoding/csv"
"errors"
"fmt"
"io"
"strings"
)
func main() {
reader := csv.NewReader(strings.NewReader("\"bolts, steel\",3\nnuts\n"))
reader.FieldsPerRecord = 2
for {
row, err := reader.Read()
if errors.Is(err, io.EOF) {
break
}
if errors.Is(err, csv.ErrFieldCount) {
fmt.Println("wrong column count")
continue
}
if err != nil {
panic(err)
}
fmt.Println(row[0], row[1])
}
}
bolts, steel 3 wrong column count
A comma inside quotes belongs to the field. By setting FieldsPerRecord, the reader also reports a row with the wrong column count.
Go documentation for csv.Reader.Read
Read an exhibit order
A curator enters a material and finish together inside a quoted item name. Read the quoted field as one CSV cell. What item name belongs to this row?
Read a studio purchase
A technician enters a cable description with a comma inside the field. Read the quoted field as one CSV cell. What item name belongs to this row?