This is a creation in Article, where the information may have evolved or changed.
The go language comes with a csv file reading module, it looks like a good, play today, is also part of the system learning go language ... ^_^
First, write a csv file
Function:
funcnewwriter (w io). Writer) *writer
func (w *writer) Flush ()
Func (w *writer) Write (record []string) (Err OS. Error)
Func (w *writer) Writeall (Records [][]string) (Err OS. Error)
For details, see official website: http://golang.org/pkg/csv/#NewWriter
In fact, write a csv file can not use these functions, directly according to the rules to write to the file, but here are the functions, or write a demo, it is also convenient for me to use later:
Package main Import ("CSV" "OS" "bytes" "FMT" ) func Main () { fileName: = "2.csv" buf: = new(bytes. Buffer) r2: = csv. Newwriter (BUF) for 0 ;i< 10 ;i++ { s: = make ([] string , 3 ) s[0] = "User ID" s[1] = "name" s[2] = "Depart" R2. Write (s) R2. Flush () } FMT. Println (BUF) fout,err: = os. Create (FileName) defer fout. Close () if err! = nil { FMT. Println (Filename,err) return } Fout. WriteString (BUF. String ()) }
Second, read the csv file
Function:
Funcnewreader (R io. Reader) *reader
Func (R *reader) Read () (Record []string, Err OS. Error)
Func (R *reader) ReadAll () (Records [][]string, Err OS. Error)
For details, see official website: http://golang.org/pkg/csv/#Reader. Read
1, the first thing to solve is to read all the contents of the file and into a string, here is the ioutil module, the specific code is as follows:
Package main Import ("Io/ioutil" "FMT" ) func Main () { B,err: = Ioutil. ReadFile ("1.csv") if err! = nil { Panic(err. String ()) } //fmt. Println (b) FMT. Printf ("%s",string(b)) }
2. Read the contents of the csv file:
Package main Import ("FMT" "CSV" "Strings" "Io/ioutil" ) func Main () {//filename: = "1.csv" FMT. Printf ("Input file name:") var fileName string FMT. SCANF ("%s", &filename) Cntb,err: = Ioutil. ReadFile (FileName) if err! = nil { Panic(err. String ()) } r2: = csv. Newreader (Strings. Newreader (string(CNTB))) ss,_: = R2. ReadAll () //fmt. PRINTLN (ss) sz: = len(ss) For i:=0; i<sz;i++{ FMT. Println (Ss[i]) } }
Well, that's all, I hope it helps.