go語言自帶的有csv文件讀取模塊,看起來好像不錯,今天玩玩,也算是系統學習go語言的一部分……^_^golang
1、寫csv文件函數
函數:學習
func NewWriter(w io.Writer) *Writer spa
func (w *Writer) Flush() 字符串
func (w *Writer) Write(record []string) (err os.Error) get
func (w *Writer) WriteAll(records [][]string) (err os.Error) string
具體見官網:http://golang.org/pkg/csv/#NewWriter it
其實寫csv文件大可沒必要用這些函數,直接按照規則寫入文件就行,不過這裏有這些函數,仍是寫個demo,也方便我之後使用:io
package main import ( "csv" "os" "bytes" "fmt" ) func main(){ fileName := "2.csv" buf := new(bytes.Buffer) r2 := csv.NewWriter(buf) for i:=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()) }
2、讀csv文件class
函數:
func NewReader(r io.Reader) *Reader
func (r *Reader) Read() (record []string, err os.Error)
func (r *Reader) ReadAll() (records [][]string, err os.Error)
具體見官網:http://golang.org/pkg/csv/#Reader.Read
一、首先要解決的是讀取文件的全部內容並存成字符串,這裏用的是ioutil模塊,具體代碼以下:
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)) }
二、讀取csv文件內容:
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]) } }