?
This document uses PHP Chinese website manual Release
import "encoding/csv"
Overview
Index
Examples
包csv讀取和寫入逗號分隔值(CSV) 文件。CSV文件有很多種,該軟件包支持RFC 4180中描述的格式。
一個csv文件包含每個記錄一個或多個字段的零個或多個記錄。每條記錄由換行符分隔。最后的記錄可以選擇跟隨一個換行符。
field1,field2,field3
白色空間被視為一個領(lǐng)域的一部分。
在換行符被無聲刪除之前,回車返回。
空白行被忽略。只有空白字符的行(不包括結(jié)尾換行符)不被視為空白行。
以引號字符開頭和結(jié)尾的字段稱為引用字段。開始和結(jié)束引號不是字段的一部分。
來源:
normal string,"quoted-field"
結(jié)果在這些領(lǐng)域
{`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的輸入??梢栽诘谝淮握{(diào)用Read或ReadAll之前更改導(dǎo)出的字段以定制細(xì)節(jié)。
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讀取一個記錄(一段字段)。如果記錄具有意外數(shù)量的字段,則Read將返回記錄以及錯誤ErrFieldCount。除此之外,Read總是返回一個非零記錄或一個非零錯誤,但不是兩者都有。如果沒有數(shù)據(jù)需要讀取,則讀取返回nil,io.EOF。如果ReuseRecord為true,則可以在多次調(diào)用Read之間共享返回的切片。
func (r *Reader) ReadAll() (records [][]string, err error)
ReadAll從r讀取所有剩余的記錄。每條記錄都是一片田地。成功的調(diào)用返回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寫入由換行符終止的記錄,并使用','作為字段分隔符。在首次調(diào)用Write或WriteAll之前,可以更改導(dǎo)出的字段以定制細(xì)節(jié)。
逗號是字段分隔符。
如果UseCRLF為true,則Writer以\ r \ n結(jié)束每個記錄而不是\ 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
錯誤報告在先前寫入或刷新期間發(fā)生的任何錯誤。
func (w *Writer) Flush()
Flush將任何緩沖的數(shù)據(jù)寫入底層的io.Writer。要檢查在刷新過程中是否發(fā)生錯誤,請調(diào)用錯誤。
func (w *Writer) Write(record []string) error
Writer寫一個CSV記錄以及任何必要的報價。記錄是一串字符串,每個字符串都是一個字段。
func (w *Writer) WriteAll(records [][]string) error
WriteAll使用Write寫入多個CSV記錄,然后調(diào)用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)}}