Library contents

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

  1. Start with CSV row containing A,2
  2. Do this Parse the two fields
  3. Result A and 2
The comma marks the field boundary. A header can supply names for those fields.

Syntax

Go 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.

From the programreader.FieldsPerRecord = 2
First output linebolts, steel 3
main.go
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])
	}
}
Output
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

Advertisements

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?

Given"clay, red",7
Worked resultclay, red

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?

Given"lead, stereo",2
Worked resultlead, stereo