Golang supports an API that handles CSV using encoding/csv package for reading CSV files. os package for open the file
create file records.csv
album, year
The White Stripes, 1999
De Stijl, 2000
White Blood Cells, 2001
Elephant, 2003
Get Behind Me Satan, 2005
Icky Thump, 2007
Under Great White Northern Lights, 2010
Live in Mississippi, 2011
Live at the Gold Dollar, 2012
Nine Miles from the White City, 2013
open a csv file
os.Open("./records.csv")
close a csv file using defer
defer csvFile.Close()
package main import ( "fmt" "encoding/csv" "io" "os" ) func main() { csvFile, err := os.Open("./records.csv") if err != nil { fmt.Println("error :",err) return } defer csvFile.Close() fileReader := csv.NewReader(csvFile) header, _ := fileReader.Read() if err != nil { fmt.Println(" error ::", err) return } fmt.Println("Headers \n",header) for i:=0 ;; i = i + 1 { record, err := fileReader.Read() if err == io.EOF { break }else if err != nil{ fmt.Println("err : ",err) } fmt.Println("row \n",i, record) } }
Output
xyz@xyz:~/Documents/golang _practices$ go build xyz@xyz:~/Documents/golang _practices$ go run csv.go Headers [album year] row 0 [The White Stripes 1999] row 1 [De Stijl 2000] row 2 [White Blood Cells 2001] row 3 [Elephant 2003] row 4 [Get Behind Me Satan 2005] row 5 [Icky Thump 2007] row 6 [Under Great White Northern Lights 2010] row 7 [Live in Mississippi 2011] row 8 [Live at the Gold Dollar 2012] row