csv

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 14, 2018 License: BSD-3-Clause Imports: 6 Imported by: 0

README

CSV

GoDoc

A Go CSV implementation inspired by Python's CSV module. It supports various CSV dialects (see below) and is fully backward compatible with the encoding/csv package in the Go standard library.

Examples

Writing

Here's a basic writing example::

    f, err := os.Create("output.csv")
    checkError(err)
    defer func() {
      err := f.Close()
      checkError(err)
    }
    w := NewWriter(f)
    w.Write([]string{
      "a",
      "b",
      "c",
    })
    w.Flush()
    // output.csv will now contains the line "a b c" with a trailing newline.

Reading

Here's a basic reading example::

f, err := os.Open('myfile.csv')
checkError(err)
defer func() {
  err := f.Close()
  checkError(err)
}

r := NewReader(f)
for {
  fields, err := r.Read()
  if err == io.EOF {
    break
  }
  checkOtherErrors(err)
  handleFields(fields)
}

To automatically detects the CSV delimiter conforming to the specifications outlined on the on the Wikipedia article. Looking through many CSV libraries code and discussion on the stackoverflow, finding that their CSV delimiter detection is limited or incomplete or containing many unneeded features. Hoping this can people solve the CSV delimiter detection problem without importing extra overhead.

Usage

package main

import (
	"github.com/eltorocorp/go-csv/detector"
	"os"
	"fmt"
)

func main()  {
	detector := detector.New()

	file, err := os.OpenFile("example.csv", os.O_RDONLY, os.ModePerm)
	if err != nil {
		os.Exit(1)
	}
	defer file.Close()

	delimiters := detector.DetectDelimiter(file, '"')
	fmt.Println(delimiters)
}

CSV dialects

To modify CSV dialect, have a look at csv.Dialect, csv.NewDialectWriter(...) and csv.NewDialectReader(...). It supports changing:

  • separator/delimiter.
  • quoting modes:
    • Always quote.
    • Never quote.
    • Quote when needed (minimal quoting).
    • Quote all non-numerical fields.
  • line terminator.
  • how quote character escaping should be done - using double escape, or using a custom escape character.

Have a look at the documentation csv_test.go for example on how to use these. All values above have sane defaults (that makes the module behave the same as the csv module in the Go standard library).

Documentation

Package documentation can be found here

Contributions

github.com/bcmcmil/go-csv

Documentation

Overview

A CSV implementation inspired by Python's CSV module. Supports custom CSV formats.

Example (ReadingWriting)
buf := bytes.Buffer{}

writer := csv.NewWriter(&buf)
writer.Write([]string{"Hello", "World", "!"})
writer.Flush()

reader := csv.NewReader(&buf)
columns, err := reader.Read()
if err != nil {
	panic(err)
}

for _, s := range columns {
	fmt.Println(s)
}
Output:

Hello
World
!

Index

Examples

Constants

View Source
const (
	QuoteDefault    = iota // See DefaultQuoting.
	QuoteAll        = iota // Quotes around every field.
	QuoteMinimal    = iota // Quotes when needed.
	QuoteNonNumeric = iota // Quotes around non-numeric fields.

	// Never quote. Use with care. Could make things unparsable.
	QuoteNone = iota
)

Values Dialect.Quoting can take.

View Source
const (
	DoubleQuoteDefault = iota // See DefaultDoubleQuote.
	DoDoubleQuote      = iota // Escape using double escape characters.
	NoDoubleQuote      = iota // Escape using escape character.
)

Values Dialect.DoubleQuote can take.

View Source
const (
	DefaultDelimiter      = ' '
	DefaultQuoting        = QuoteMinimal
	DefaultDoubleQuote    = DoDoubleQuote
	DefaultEscapeChar     = '\\'
	DefaultQuoteChar      = '"'
	DefaultLineTerminator = "\n"
)

Default dialect.

Variables

This section is empty.

Functions

This section is empty.

Types

type Dialect

type Dialect struct {
	// The delimiter that separates each field from another. Defaults to
	// DefaultDelimiter.
	Delimiter rune
	// What quoting mode to use. Defaults to DefaultQuoting.
	Quoting int
	// How to escape quotes. Defaults to DefaultDoubleQuote.
	DoubleQuote int
	// Character to use for escaping. Only used if DoubleQuote==NoDoubleQuote.
	// Defaults to DefaultEscapeChar.
	EscapeChar rune
	// Character to use as quotation mark around quoted fields. Defaults to
	// DefaultQuoteChar.
	QuoteChar rune
	// String that separates each record in a CSV file. Defaults to
	// DefaultLineTerminator.
	LineTerminator string
}

A Dialect specifies the format of a CSV file. This structure is used by a Reader or Writer to know how to operate on the file they are reading/writing.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

A Reader reads records from a CSV-encoded file.

Can be created by calling either NewReader or using NewDialectReader.

func NewDialectReader

func NewDialectReader(r io.Reader, opts Dialect) *Reader

Create a custom CSV reader.

func NewReader

func NewReader(r io.Reader) *Reader

Creates a reader that conforms to RFC 4180 and behaves identical as a encoding/csv.Reader.

See `Default*` constants for default dialect used.

func (*Reader) Read

func (r *Reader) Read() ([]string, error)

Read reads one record from r. The record is a slice of strings with each string representing one field.

func (*Reader) ReadAll

func (r *Reader) ReadAll() ([][]string, error)

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

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

A Writer writes records to a CSV encoded file.

Can be created by calling either NewWriter or using NewDialectWriter.

func NewDialectWriter

func NewDialectWriter(w io.Writer, opts Dialect) Writer

Create a custom CSV writer.

func NewWriter

func NewWriter(w io.Writer) Writer

Create a writer that conforms to RFC 4180 and behaves identical as a encoding/csv.Reader.

See `Default*` constants for default dialect used.

func (Writer) Error

func (w Writer) Error() error

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

func (Writer) Flush

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

func (w Writer) Write(record []string) (err 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

func (w Writer) WriteAll(records [][]string) (err error)

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

Directories

Path Synopsis
Helpers that makes it easy to build CSV dialects.
Helpers that makes it easy to build CSV dialects.
Interfaces shared among go-csv and the Go standard library's encoding/csv.
Interfaces shared among go-csv and the Go standard library's encoding/csv.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL