Golang : How to read CSV file
One way or another, CSV file is going to be part and parcel of a developer life. A programmer will bound to meet up with CSV file one day. In this tutorial, we will show you how to read CSV file wtih Go. Below is a simple code in Go demonstrating the capability.
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
csvfile, err := os.Open("somecsvfile.csv")
if err != nil {
fmt.Println(err)
return
}
defer csvfile.Close()
reader := csv.NewReader(csvfile)
reader.FieldsPerRecord = -1 // see the Reader struct information below
rawCSVdata, err := reader.ReadAll()
if err != nil {
fmt.Println(err)
os.Exit(1)
}
// sanity check, display to standard output
for _, each := range rawCSVdata {
fmt.Printf("email : %s and timestamp : %s\n", each[0], each[1])
}
}
See how to load CSV values into Struct at https://www.socketloop.com/tutorials/how-to-unmarshal-or-load-csv-record-into-struct-go
The CSV file contains the following data
more somecsvfile.csv
"jenniferlcl@*****.com","2012-07-03 18:38:06"
"norazlinjumali@*****.com","2010-06-26 19:46:08"
"wilfred5571@*****.com","2010-07-02 21:49:55"
"nas_kas81@*****.com","2010-07-06 12:49:31"
"tammyu3622@*****.com","2010-07-06 13:55:21"
"wakrie@*****.com","2012-03-02 11:00:59"
"yst.shirin@*****.com","2010-07-07 10:19:11"
"annl_107@*****.com","2010-07-07 20:55:59"
"jen_5831@*****.com","2010-07-07 21:12:27"
"hsheyli@*****.com","2011-09-07 00:39:11"
The Reader has the following data structure :
type Reader struct {
Comma rune // field delimiter (set to ',' by NewReader)
Comment rune // comment character for start of line
FieldsPerRecord int // number of expected fields per record
LazyQuotes bool // allow lazy quotes
TrailingComma bool // ignored; here for backwards compatibility
TrimLeadingSpace bool // trim leading space
// contains filtered or unexported fields
}
Reference:
See also : Read a XML file in Go
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+6.2k Golang : Handling image beyond OpenCV video capture boundary
+6k Golang : How to get capacity of a slice or array?
+8.6k Golang : GMail API create and send draft with simple upload attachment example
+20.4k PHP : Convert(cast) int to double/float
+6.6k Mac OSX : Find large files by size
+22k Golang : Read directory content with filepath.Walk()
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+5.4k Fix fatal error: evacuation not done in time problem
+5.3k Golang : Detect words using using consecutive letters in a given string
+12k Golang : How to check if a string starts or ends with certain characters or words?
+4.8k Linux/Unix/MacOSX : Find out which application is listening to port 80 or use which IP version