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.4k Golang : Missing Bazaar command
+20.6k Golang : Convert PNG transparent background image to JPG or JPEG image
+5.5k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+5.5k Unix/Linux/MacOSx : Get local IP address
+9.9k Golang : Use regular expression to get all upper case or lower case characters example
+18.5k Golang : Display list of time zones with GMT
+18.3k Golang : Iterating Elements Over A List
+10.7k Golang : Sieve of Eratosthenes algorithm
+14.4k Golang : Get URI segments by number and assign as variable example
+20.8k Golang : For loop continue,break and range
+6.1k Unix/Linux : Use netstat to find out IP addresses served by your website server
+7.8k Golang : Check from web if Go application is running or not