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
+14.2k Golang : Send email with attachment(RFC2822) using Gmail API example
+9.5k Golang : Qt get screen resolution and display on center example
+7.6k Swift : Convert (cast) String to Double
+7.2k Golang : Gorrila set route name and get the current route name
+15k Golang : Get timezone offset from date or timestamp
+6.9k Nginx : How to block user agent ?
+5.9k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+21.3k SSL : How to check if current certificate is sha1 or sha2
+8.3k Linux/Unix : fatal: the Postfix mail system is already running
+11.4k Golang : Gorilla web tool kit secure cookie example
+29.5k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+13.2k Facebook PHP getUser() returns 0