Created
November 5, 2019 21:13
-
-
Save kjk/b1fb4a2a2f6c6d2e317f540928d890e8 to your computer and use it in GitHub Desktop.
Reading records from CSV file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// :collection Essential Go | |
package main | |
import ( | |
"bytes" | |
"encoding/csv" | |
"fmt" | |
"io" | |
"log" | |
) | |
var ( | |
csvData = `date,open,high,low,close,volume,Name | |
2013-02-08,15.07,15.12,14.63,14.75,8407500,AAL | |
2013-02-11,14.89,15.01,14.26,14.46,8882000,AAL | |
2013-02-12,14.45,14.51,14.1,14.27,8126000,AAL | |
2013-02-13,14.3,14.94,14.25,14.66,10259500,AAL | |
`) | |
func main() { | |
// :show start | |
buf := bytes.NewBufferString(csvData) | |
r := csv.NewReader(buf) | |
var record []string | |
nRecords := 0 | |
var err error | |
for { | |
record, err = r.Read() | |
if err != nil { | |
if err == io.EOF { | |
err = nil | |
} | |
break | |
} | |
nRecords++ | |
if nRecords < 5 { | |
fmt.Printf("Record: %#v\n", record) | |
} | |
} | |
if err != nil { | |
log.Fatalf("r.Read() failed with '%s'\n", err) | |
} | |
fmt.Printf("Read %d records\n", nRecords) | |
// :show end | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment