Skip to content

Instantly share code, notes, and snippets.

@spidergears
Last active August 29, 2015 14:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spidergears/f645a1d17e463ab6c100 to your computer and use it in GitHub Desktop.
Save spidergears/f645a1d17e463ab6c100 to your computer and use it in GitHub Desktop.
//Simple CSV reader
package main
import (
"encoding/csv" //Package csv reads and writes comma-separated values (CSV) files.
"fmt" //Package fmt implements formatted I/O with functions analogous to C's printf and scanf.
"io" //Package io provides basic interfaces to I/O primitives.
"os" //Package os provides a platform-independent interface to operating system functionality.
)
// Ref http://golang.org/pkg/ for more on packages and links to documentation
func main() {
//Check for command-line argument filename.
//Ignore additional arguments.
if len(os.Args) < 2 {
fmt.Printf("Error: Source file name is required\n")
fmt.Println("Usage:", os.Args[0], "<filename> \n")
return
}
file, err := os.Open(os.Args[1])
if err != nil {
fmt.Println("Error:", err)
return
}
// deferred call to Close() at the end of current method
defer file.Close()
//get a new cvsReader for reading file
reader := csv.NewReader(file)
//Configure reader options Ref http://golang.org/src/pkg/encoding/csv/reader.go?s=#L81
reader.Comma = ';' //field delimiter
reader.Comment = '#' //Comment character
reader.FieldsPerRecord = -1 //Number of records per record. Set to Negative value for variable
reader.TrimLeadingSpace = true
lineCount := 1
for {
// read just one record, but we could ReadAll() as well
record, err := reader.Read()
// end-of-file is fitted into err
if err == io.EOF {
break
} else if err != nil {
fmt.Println("Error:", err)
lineCount += 1
reader.Read()
continue
}
// record is array of strings Ref http://golang.org/src/pkg/encoding/csv/reader.go?s=#L134
fmt.Printf("Record %d: %s\n", lineCount, record)
lineCount += 1
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment