Skip to content
Tutorials Center
My learning

Topics

Go Reference ยท Encoding and Data Formats

The Go encoding/csv package

Reference for Go's encoding/csv package: Reader, Writer, quoting rules, delimiters, field counts, ReadAll versus Read, and common CSV mistakes, with live examples.

The encoding/csv package reads and writes comma-separated values as described in RFC 4180. It understands quoted fields, commas and line breaks inside quotes, and doubled quotes ("") as an escaped quote. You never need to split CSV lines by hand.

Both directions work with records, which are plain []string slices. csv.NewReader wraps an io.Reader, and csv.NewWriter wraps an io.Writer. The package does no type conversion: every field is a string, so use strconv to turn numbers into int or float64.

Go
r := csv.NewReader(strings.NewReader("name,age\nAnn,31\n"))
records, err := r.ReadAll() // [][]string

Try it

Go Reading records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go Writing, quoting and field-count errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Syntax

Go
func NewReader(r io.Reader) *Reader
func (r *Reader) Read() (record []string, err error)
func (r *Reader) ReadAll() (records [][]string, err error)
func (r *Reader) FieldPos(field int) (line, column int)
func (r *Reader) InputOffset() int64

func NewWriter(w io.Writer) *Writer
func (w *Writer) Write(record []string) error
func (w *Writer) WriteAll(records [][]string) error
func (w *Writer) Flush()
func (w *Writer) Error() error

Reader fields you can set before the first read:

Field Description
Comma Field delimiter, a rune. Default ,. Must not be \r, \n, the quote character or the Unicode replacement character.
Comment If non-zero, lines starting with this rune are skipped.
FieldsPerRecord 0 (default): every record must have as many fields as the first. Positive: exactly that many. Negative: any number is accepted.
LazyQuotes Allow a quote inside an unquoted field and a non-doubled quote inside a quoted field.
TrimLeadingSpace Ignore leading white space in a field.
ReuseRecord Read may return the same backing slice each time, which saves allocations. Copy what you keep.

Writer has Comma (delimiter) and UseCRLF (end lines with \r\n instead of \n).

Errors and edge cases:

  • Read returns io.EOF at the end of the input. ReadAll treats a clean end as success and returns nil as the error.
  • A wrong number of fields returns the record and an error that wraps csv.ErrFieldCount, so you can decide to keep the record.
  • Malformed quoting returns a *csv.ParseError with Line, StartLine, Column and the cause in Err (for example csv.ErrBareQuote or csv.ErrQuote).
  • Blank lines are skipped. A line with only a quoted empty string ("") is a record with one empty field.

Usage notes

  • Always call Flush. Writer buffers its output. After the last Write, call w.Flush() and then check w.Error(). WriteAll flushes for you.
  • Quoting is automatic on writing. A field is quoted when it contains the delimiter, a quote, a newline, or starts with a space. Other fields are written as they are.
  • Headers are your job. The first record is not special. Read it yourself and build a map[string]int from names to columns when the order may change.
  • Big files: loop with Read instead of ReadAll, which holds every record in memory at once.
  • Other delimiters: set Comma = '\t' for TSV or ';' for the semicolon style common in some European locales.
  • Byte order marks: a UTF-8 BOM at the start of a file (typical for Excel exports) stays in the first field. Strip it before parsing.
  • Spreadsheet formula injection: if you export user text that opens in a spreadsheet, a field starting with =, +, - or @ can be executed as a formula. The package does not guard against it.