version: 1.10

package csv

import "encoding/csv"

Overview

Package csv reads and writes comma-separated values (CSV) files. There are many kinds of CSV files; this package supports the format described in RFC 4180.

A csv file contains zero or more records of one or more fields per record. Each record is separated by the newline character. The final record may optionally be followed by a newline character.

  1. field1,field2,field3

White space is considered part of a field.

Carriage returns before newline characters are silently removed.

Blank lines are ignored. A line with only whitespace characters (excluding the ending newline character) is not considered a blank line.

Fields which start and stop with the quote character “ are called quoted-fields. The beginning and ending quote are not part of the field.

The source:

  1. normal string,"quoted-field"

results in the fields

  1. {`normal string`, `quoted-field`}

Within a quoted-field a quote character followed by a second quote character is considered a single quote.

  1. "the ""word"" is true","a ""quoted-field"""

results in

  1. {`the "word" is true`, `a "quoted-field"`}

Newlines and commas may be included in a quoted-field

  1. "Multi-line
  2. field","comma is ,"

results in

  1. {`Multi-line
  2. field`, `comma is ,`}

Index

Examples

Package files

reader.go writer.go

Variables

  1. var (
  2. ErrTrailingComma = errors.New("extra delimiter at end of line") // Deprecated: No longer used.
  3. ErrBareQuote = errors.New("bare \" in non-quoted-field")
  4. ErrQuote = errors.New("extraneous or missing \" in quoted-field")
  5. ErrFieldCount = errors.New("wrong number of fields")
  6. )

These are the errors that can be returned in ParseError.Err.

type ParseError

  1. type ParseError struct {
  2. StartLine int // Line where the record starts
  3. Line int // Line where the error occurred
  4. Column int // Column (rune index) where the error occurred
  5. Err error // The actual error
  6. }

A ParseError is returned for parsing errors. Line numbers are 1-indexed and columns are 0-indexed.

func (*ParseError) Error

  1. func (e *ParseError) Error() string

type Reader

  1. type Reader struct {
  2. // Comma is the field delimiter.
  3. // It is set to comma (',') by NewReader.
  4. // Comma must be a valid rune and must not be \r, \n,
  5. // or the Unicode replacement character (0xFFFD).
  6. Comma rune
  7.  
  8. // Comment, if not 0, is the comment character. Lines beginning with the
  9. // Comment character without preceding whitespace are ignored.
  10. // With leading whitespace the Comment character becomes part of the
  11. // field, even if TrimLeadingSpace is true.
  12. // Comment must be a valid rune and must not be \r, \n,
  13. // or the Unicode replacement character (0xFFFD).
  14. // It must also not be equal to Comma.
  15. Comment rune
  16.  
  17. // FieldsPerRecord is the number of expected fields per record.
  18. // If FieldsPerRecord is positive, Read requires each record to
  19. // have the given number of fields. If FieldsPerRecord is 0, Read sets it to
  20. // the number of fields in the first record, so that future records must
  21. // have the same field count. If FieldsPerRecord is negative, no check is
  22. // made and records may have a variable number of fields.
  23. FieldsPerRecord int
  24.  
  25. // If LazyQuotes is true, a quote may appear in an unquoted field and a
  26. // non-doubled quote may appear in a quoted field.
  27. LazyQuotes bool
  28.  
  29. // If TrimLeadingSpace is true, leading white space in a field is ignored.
  30. // This is done even if the field delimiter, Comma, is white space.
  31. TrimLeadingSpace bool
  32.  
  33. // ReuseRecord controls whether calls to Read may return a slice sharing
  34. // the backing array of the previous call's returned slice for performance.
  35. // By default, each call to Read returns newly allocated memory owned by the caller.
  36. ReuseRecord bool
  37.  
  38. TrailingComma bool // Deprecated: No longer used.
  39. // contains filtered or unexported fields
  40. }

A Reader reads records from a CSV-encoded file.

As returned by NewReader, a Reader expects input conforming to RFC 4180. The exported fields can be changed to customize the details before the first call to Read or ReadAll.

The Reader converts all \r\n sequences in its input to plain \n, including in multiline field values, so that the returned data does not depend on which line-ending convention an input file uses.

Example:

  1. in := `first_name,last_name,username
  2. "Rob","Pike",rob
  3. Ken,Thompson,ken
  4. "Robert","Griesemer","gri"
  5. `
  6. r := csv.NewReader(strings.NewReader(in))
  7. for {
  8. record, err := r.Read()
  9. if err == io.EOF {
  10. break
  11. }
  12. if err != nil {
  13. log.Fatal(err)
  14. }
  15. fmt.Println(record)
  16. }
  17. // Output:
  18. // [first_name last_name username]
  19. // [Rob Pike rob]
  20. // [Ken Thompson ken]
  21. // [Robert Griesemer gri]

Example:

  1. in := `first_name;last_name;username
  2. "Rob";"Pike";rob
  3. # lines beginning with a # character are ignored
  4. Ken;Thompson;ken
  5. "Robert";"Griesemer";"gri"
  6. `
  7. r := csv.NewReader(strings.NewReader(in))
  8. r.Comma = ';'
  9. r.Comment = '#'
  10. records, err := r.ReadAll()
  11. if err != nil {
  12. log.Fatal(err)
  13. }
  14. fmt.Print(records)
  15. // Output:
  16. // [[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]

func NewReader

  1. func NewReader(r io.Reader) *Reader

NewReader returns a new Reader that reads from r.

func (*Reader) Read

  1. func (r *Reader) Read() (record []string, err error)

Read reads one record (a slice of fields) from r. If the record has an unexpected number of fields, Read returns the record along with the error ErrFieldCount. Except for that case, Read always returns either a non-nil record or a non-nil error, but not both. If there is no data left to be read, Read returns nil, io.EOF. If ReuseRecord is true, the returned slice may be shared between multiple calls to Read.

func (*Reader) ReadAll

  1. func (r *Reader) ReadAll() (records [][]string, err error)

ReadAll reads all the remaining records from r. Each record is a slice of fields. A successful call returns err == nil, not err == io.EOF. Because ReadAll is defined to read until EOF, it does not treat end of file as an error to be reported.

Example:

  1. in := `first_name,last_name,username
  2. "Rob","Pike",rob
  3. Ken,Thompson,ken
  4. "Robert","Griesemer","gri"
  5. `
  6. r := csv.NewReader(strings.NewReader(in))
  7. records, err := r.ReadAll()
  8. if err != nil {
  9. log.Fatal(err)
  10. }
  11. fmt.Print(records)
  12. // Output:
  13. // [[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]

type Writer

  1. type Writer struct {
  2. Comma rune // Field delimiter (set to ',' by NewWriter)
  3. UseCRLF bool // True to use \r\n as the line terminator
  4. // contains filtered or unexported fields
  5. }

A Writer writes records to a CSV encoded file.

As returned by NewWriter, a Writer writes records terminated by a newline and uses ‘,’ as the field delimiter. The exported fields can be changed to customize the details before the first call to Write or WriteAll.

Comma is the field delimiter.

If UseCRLF is true, the Writer ends each output line with \r\n instead of \n.

Example:

  1. records := [][]string{
  2. {"first_name", "last_name", "username"},
  3. {"Rob", "Pike", "rob"},
  4. {"Ken", "Thompson", "ken"},
  5. {"Robert", "Griesemer", "gri"},
  6. }
  7. w := csv.NewWriter(os.Stdout)
  8. for _, record := range records {
  9. if err := w.Write(record); err != nil {
  10. log.Fatalln("error writing record to csv:", err)
  11. }
  12. }
  13. // Write any buffered data to the underlying writer (standard output).
  14. w.Flush()
  15. if err := w.Error(); err != nil {
  16. log.Fatal(err)
  17. }
  18. // Output:
  19. // first_name,last_name,username
  20. // Rob,Pike,rob
  21. // Ken,Thompson,ken
  22. // Robert,Griesemer,gri

func NewWriter

  1. func NewWriter(w io.Writer) *Writer

NewWriter returns a new Writer that writes to w.

func (*Writer) Error

  1. func (w *Writer) Error() error

Error reports any error that has occurred during a previous Write or Flush.

func (*Writer) Flush

  1. func (w *Writer) Flush()

Flush writes any buffered data to the underlying io.Writer. To check if an error occurred during the Flush, call Error.

func (*Writer) Write

  1. func (w *Writer) Write(record []string) error

Writer writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field.

func (*Writer) WriteAll

  1. func (w *Writer) WriteAll(records [][]string) error

WriteAll writes multiple CSV records to w using Write and then calls Flush.

Example:

  1. records := [][]string{
  2. {"first_name", "last_name", "username"},
  3. {"Rob", "Pike", "rob"},
  4. {"Ken", "Thompson", "ken"},
  5. {"Robert", "Griesemer", "gri"},
  6. }
  7. w := csv.NewWriter(os.Stdout)
  8. w.WriteAll(records) // calls Flush internally
  9. if err := w.Error(); err != nil {
  10. log.Fatalln("error writing csv:", err)
  11. }
  12. // Output:
  13. // first_name,last_name,username
  14. // Rob,Pike,rob
  15. // Ken,Thompson,ken
  16. // Robert,Griesemer,gri