©
Dieses Dokument verwendet PHP-Handbuch für chinesische Websites Freigeben
import "encoding/csv"
Overview
Index
Examples
包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 ,"
results in
{`Multi-line field`, `comma is ,`}
Variables
type ParseError
func (e *ParseError) Error() string
type Reader
func NewReader(r io.Reader) *Reader
func (r *Reader) Read() (record []string, err error)
func (r *Reader) ReadAll() (records [][]string, err error)
type Writer
func NewWriter(w io.Writer) *Writer
func (w *Writer) Error() error
func (w *Writer) Flush()
func (w *Writer) Write(record []string) error
func (w *Writer) WriteAll(records [][]string) error
Reader Reader.ReadAll Reader(选项)Writer Writer.WriteAll
reader.go writer.go
这些是可以在ParseError.Error中返回的错误
var ( ErrTrailingComma = errors.New("extra delimiter at end of line") // no longer used ErrBareQuote = errors.New("bare \" in non-quoted-field") ErrQuote = errors.New("extraneous \" in field") ErrFieldCount = errors.New("wrong number of fields in line"))
解析错误返回ParseError。第一行是1.第一列是0。
type ParseError struct { Line int // Line where the error occurred Column int // Column (rune index) where the error occurred Err error // The actual error}
func (e *ParseError) Error() string
Reader从CSV编码的文件中读取记录。
正如NewReader返回的那样,Reader期望符合RFC 4180的输入。可以在第一次调用Read或ReadAll之前更改导出的字段以定制细节。
type Reader struct { // Comma is the field delimiter. // It is set to comma (',') by NewReader. 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 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 TrailingComma bool // ignored; here for backwards compatibility // 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 // contains filtered or unexported fields}
package mainimport ("encoding/csv""fmt""io""log""strings")func main() {in := `first_name,last_name,username "Rob","Pike",rob Ken,Thompson,ken "Robert","Griesemer","gri" ` r := csv.NewReader(strings.NewReader(in))for { record, err := r.Read()if err == io.EOF {break}if err != nil { log.Fatal(err)} fmt.Println(record)}}
此示例显示如何配置csv.Reader以处理其他类型的CSV文件。
package mainimport ("encoding/csv""fmt""log""strings")func main() {in := `first_name;last_name;username "Rob";"Pike";rob # lines beginning with a # character are ignored Ken;Thompson;ken "Robert";"Griesemer";"gri" ` r := csv.NewReader(strings.NewReader(in)) r.Comma = ';' r.Comment = '#' records, err := r.ReadAll()if err != nil { log.Fatal(err)} fmt.Print(records)}
func NewReader(r io.Reader) *Reader
NewReader返回一个新的从r读取的Reader。
func (r *Reader) Read() (record []string, err error)
读取从r读取一个记录(一段字段)。如果记录具有意外数量的字段,则Read将返回记录以及错误ErrFieldCount。除此之外,Read总是返回一个非零记录或一个非零错误,但不是两者都有。如果没有数据需要读取,则读取返回nil,io.EOF。如果ReuseRecord为true,则可以在多次调用Read之间共享返回的切片。
func (r *Reader) ReadAll() (records [][]string, err error)
ReadAll从r读取所有剩余的记录。每条记录都是一片田地。成功的调用返回err == nil,而不是err == io.EOF。由于ReadAll被定义为读取直到EOF,因此它不会将文件末尾视为要报告的错误。
package mainimport ("encoding/csv""fmt""log""strings")func main() {in := `first_name,last_name,username "Rob","Pike",rob Ken,Thompson,ken "Robert","Griesemer","gri" ` r := csv.NewReader(strings.NewReader(in)) records, err := r.ReadAll()if err != nil { log.Fatal(err)} fmt.Print(records)}
Writer将记录写入CSV编码文件。
如NewWriter返回的,Writer写入由换行符终止的记录,并使用','作为字段分隔符。在首次调用Write或WriteAll之前,可以更改导出的字段以定制细节。
逗号是字段分隔符。
如果UseCRLF为true,则Writer以\ r \ n结束每个记录而不是\ n。
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}
package mainimport ("encoding/csv""log""os")func main() { records := [][]string{{"first_name", "last_name", "username"},{"Rob", "Pike", "rob"},{"Ken", "Thompson", "ken"},{"Robert", "Griesemer", "gri"},} w := csv.NewWriter(os.Stdout)for _, record := range records {if err := w.Write(record); err != nil { log.Fatalln("error writing record to csv:", err)}}// Write any buffered data to the underlying writer (standard output). w.Flush()if err := w.Error(); err != nil { log.Fatal(err)}}
func NewWriter(w io.Writer) *Writer
NewWriter返回一个写入w的新Writer。
func (w *Writer) Error() error
错误报告在先前写入或刷新期间发生的任何错误。
func (w *Writer) Flush()
Flush将任何缓冲的数据写入底层的io.Writer。要检查在刷新过程中是否发生错误,请调用错误。
func (w *Writer) Write(record []string) error
Writer写一个CSV记录以及任何必要的报价。记录是一串字符串,每个字符串都是一个字段。
func (w *Writer) WriteAll(records [][]string) error
WriteAll使用Write写入多个CSV记录,然后调用Flush。
package mainimport ("encoding/csv""log""os")func main() { records := [][]string{{"first_name", "last_name", "username"},{"Rob", "Pike", "rob"},{"Ken", "Thompson", "ken"},{"Robert", "Griesemer", "gri"},} w := csv.NewWriter(os.Stdout) w.WriteAll(records) // calls Flush internallyif err := w.Error(); err != nil { log.Fatalln("error writing csv:", err)}}