Last active
August 29, 2015 14:06
-
-
Save spidergears/f645a1d17e463ab6c100 to your computer and use it in GitHub Desktop.
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
//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