csv.NewWriter, Writer.Write, Writer.Flush, csv.NewReader, Reader.Read, Reader.ReadAll
func NewWriter(w io.Writer) *Writer
func (w *Writer) Write(record []string) error
func (w *Writer) Flush()
func (w *Writer) Error() error
func NewReader(r io.Reader) *Reader
func (r *Reader) Read() (record []string, err error)
func (r *Reader) ReadAll() (records [][]string, err error)Write quoted CSV, then read it back with a field-count check. A mismatch still returns the record, together with ErrFieldCount.
| Parameter | Description |
|---|---|
w / r | An io.Writer or io.Reader. The example uses a bytes.Buffer and strings.Reader, not a user file. |
FieldsPerRecord | 0 (the default) locks the width to the first record. A positive value requires that many fields. A negative value disables the check. |
Returns: Write returns an error from the underlying writer, if any. Flush has no result; check Error afterwards. Read returns the record and an error; at the end of the input, the error is io.EOF. ReadAll returns every record or the first error.
Errors
csv.ErrFieldCount— Returned, wrapped in a *ParseError, when the record width does not match FieldsPerRecord. Official documentation: Read still returns the record. The measured Error text on Go 1.24.0 is "record on line 2: wrong number of fields".
- The quoted output "a,b",c was measured on Go 1.24.0 with the default comma delimiter and a trailing newline after each record.
package main
import (
"bytes"
"encoding/csv"
"errors"
"fmt"
"strings"
)
func main() {
var buf bytes.Buffer
w := csv.NewWriter(&buf)
_ = w.Write([]string{"a,b", "c"})
_ = w.Write([]string{"d", "e"})
w.Flush()
fmt.Print(buf.String())
fmt.Println(w.Error())
r := csv.NewReader(strings.NewReader("a,b\n1,2,3\n"))
rec, err := r.Read()
fmt.Println(rec, err)
rec, err = r.Read()
fmt.Println(rec, err)
fmt.Println(errors.Is(err, csv.ErrFieldCount))
flexible := csv.NewReader(strings.NewReader("a,b\n1,2,3\n"))
flexible.FieldsPerRecord = -1
all, err := flexible.ReadAll()
fmt.Println(all, err)
}Expected output
"a,b",c
d,e
<nil>
[a b] <nil>
[1 2 3] record on line 2: wrong number of fields
true
[[a b] [1 2 3]] <nil>