Golang : How to read CSV file

Tags : csv golang

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 (

 func main() {

 csvfile, err := os.Open("somecsvfile.csv")

 if err != nil {

 defer csvfile.Close()

 reader := csv.NewReader(csvfile)

 reader.FieldsPerRecord = -1 // see the Reader struct information below

 rawCSVdata, err := reader.ReadAll()

 if err != nil {

 // 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


Golang CSV Package

  See also : Read a XML file in Go

Tags : csv golang

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.