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.
r := csv.NewReader(strings.NewReader("name,age\nAnn,31\n")) records, err := r.ReadAll() // [][]string
Try it
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.
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
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:
Readreturnsio.EOFat the end of the input.ReadAlltreats a clean end as success and returnsnilas 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.ParseErrorwithLine,StartLine,Columnand the cause inErr(for examplecsv.ErrBareQuoteorcsv.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.Writerbuffers its output. After the lastWrite, callw.Flush()and then checkw.Error().WriteAllflushes 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]intfrom names to columns when the order may change. - Big files: loop with
Readinstead ofReadAll, 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.