Package csv

import "encoding/csv"
Overview
Index
Examples

Overview ▾

程序包csv读取和写入逗号分隔值(CSV)文件. CSV文件种类繁多; 该软件包支持RFC 4180中描述的格式.

一个csv文件包含零个或多个记录,每个记录一个或多个字段. 每个记录都由换行符分隔. 最终记录可以选择后跟换行符.

field1,field2,field3

空白被认为是字段的一部分.

回车符会在默默删除换行符之前返回.

空行将被忽略. 仅包含空格字符(不包括换行符)的行不被视为空白行.

以引号字符开头和结尾的字段称为带引号的字段.开头和结尾的引号不是该字段的一部分.

来源:

normal string,"quoted-field"

结果在领域

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

在带引号的字段中,引号字符后跟第二个引号字符被视为单引号.

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

results in

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

引号字段中可能包含换行符和逗号

"Multi-line
field","comma is ,"

结果是

{`Multi-line
field`, `comma is ,`}

Variables

这些是可以在ParseError.Err中返回的错误.

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

type ParseError

返回ParseError以解析错误. 行号是1索引,列是0索引.

type ParseError struct {
    StartLine int   // Line where the record starts; added in Go 1.10
    Line      int   // Line where the error occurred
    Column    int   // Column (rune index) where the error occurred
    Err       error // The actual error
}

func (*ParseError) Error

func (e *ParseError) Error() string

func (*ParseError) Unwrap 1.13

func (e *ParseError) Unwrap() error

type Reader

阅读器从CSV编码文件中读取记录.

如NewReader所返回的,阅读器期望输入符合RFC4180.在第一次调用Read或ReadAll之前,可以更改导出的字段以自定义详细信息.

阅读器将其输入中的所有\ r \ n序列转换为普通\ n,包括多行字段值,以便返回的数据不取决于输入文件使用哪种行尾约定.

type Reader struct {
    // Comma is the field delimiter.
    // It is set to comma (',') by NewReader.
    // Comma must be a valid rune and must not be \r, \n,
    // or the Unicode replacement character (0xFFFD).
    Comma rune

    // Comment, if not 0, is the comment character. Lines beginning with the
    // Comment character without preceding whitespace are ignored.
    // With leading whitespace the Comment character becomes part of the
    // field, even if TrimLeadingSpace is true.
    // Comment must be a valid rune and must not be \r, \n,
    // or the Unicode replacement character (0xFFFD).
    // It must also not be equal to Comma.
    Comment rune

    // FieldsPerRecord is the number of expected fields per record.
    // If FieldsPerRecord is positive, Read requires each record to
    // have the given number of fields. If FieldsPerRecord is 0, Read sets it to
    // the number of fields in the first record, so that future records must
    // have the same field count. If FieldsPerRecord is negative, no check is
    // made and records may have a variable number of fields.
    FieldsPerRecord int

    // If LazyQuotes is true, a quote may appear in an unquoted field and a
    // non-doubled quote may appear in a quoted field.
    LazyQuotes bool

    // If TrimLeadingSpace is true, leading white space in a field is ignored.
    // This is done even if the field delimiter, Comma, is white space.
    TrimLeadingSpace bool

    // ReuseRecord controls whether calls to Read may return a slice sharing
    // the backing array of the previous call's returned slice for performance.
    // By default, each call to Read returns newly allocated memory owned by the caller.
    ReuseRecord bool // Go 1.9

    TrailingComma bool // Deprecated: No longer used.
    // contains filtered or unexported fields
}

Example

[first_name last_name username]
[Rob Pike rob]
[Ken Thompson ken]
[Robert Griesemer gri]

示例(选项)

本示例说明如何将csv.Reader配置为处理其他类型的CSV文件.

[[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]

func NewReader

func NewReader(r io.Reader) *Reader

NewReader返回一个从r读取的新Reader.

func (*Reader) Read

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

读取从r读取一条记录(一片字段). 如果记录的字段数量超出预期,则Read会返回记录以及错误ErrFieldCount. 除这种情况外,Read总是返回非空记录或非空错误,但不会同时返回两者. 如果没有要读取的数据,则Read返回nil io.EOF. 如果ReuseRecord为true,则可以在多个Read调用之间共享返回的slice.

func (*Reader) ReadAll

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

ReadAll从r读取所有剩余的记录. 每个记录都是一片字段. 成功的调用将返回err == nil,而不是err == io.EOF. 因为ReadAll被定义为在EOF之前读取,所以它不会将文件结尾视为要报告的错误.

Example

[[first_name last_name username] [Rob Pike rob] [Ken Thompson ken] [Robert Griesemer gri]]

type Writer

Writer使用CSV编码写入记录.

由NewWriter返回时,Writer写入以换行符终止的记录,并使用","作为字段定界符. 在第一次调用Write或WriteAll之前,可以更改导出的字段以自定义详细信息.

逗号是字段定界符.

如果UseCRLF为true,则Writer用\ r \ n而不是\ n结束每条输出行.

单个记录的写入被缓冲. 写入所有数据之后,客户端应调用Flush方法以确保所有数据都已转发到基础io.Writer. 发生的任何错误都应通过调用Error方法进行检查.

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

Example

first_name,last_name,username
Rob,Pike,rob
Ken,Thompson,ken
Robert,Griesemer,gri

func NewWriter

func NewWriter(w io.Writer) *Writer

NewWriter返回一个写入w的新Writer.

func (*Writer) Error 1.1

func (w *Writer) Error() error

错误报告上一次写入或刷新期间发生的任何错误.

func (*Writer) Flush

func (w *Writer) Flush()

刷新会将所有缓冲的数据写入基础io.Writer. 要检查刷新期间是否发生错误,请调用错误.

func (*Writer) Write

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

Write将单个CSV记录连同任何必要的引用一起写入w. 记录是一片字符串,每个字符串是一个字段. 写操作被缓冲,因此必须最终调用Flush以确保将记录写到基础io.Writer.

func (*Writer) WriteAll

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

WriteAll使用Write将多个CSV记录写入w,然后调用Flush,从Flush返回任何错误.

Example

first_name,last_name,username
Rob,Pike,rob
Ken,Thompson,ken
Robert,Griesemer,gri

by  ICOPY.SITE