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
+16.2k Golang : Get IP addresses of a domain name
+7.6k Setting $GOPATH environment variable for Unix/Linux and Windows
+6.5k Golang : Derive cryptographic key from passwords with Argon2
+22.6k Golang : Calculate time different
+5.5k Fix yum-complete-transaction error
+14.1k Android Studio : Use image as AlertDialog title with custom layout example
+24.7k Golang : Create PDF file from HTML file
+9.4k Golang : How to generate Code 39 barcode?
+9.9k Golang : Compare files modify date example
+10.1k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+4.5k Golang : How to pass data between controllers with JSON Web Token
+11.1k Golang : Post data with url.Values{}