In this post we are going to read CSV (Comma Separated Value) file using golang, In many cases we have to read csv file for generating report. csv files are mostly used in web production for handling many config file and server side changes and also its useful in case of export and import data.
In industry there are lot of scenario come like taking data from db mostly we use those csv file to import or export dynamic data.
In data-science or data analysis scenario we get data in format of csv and generate chart report and share those data in csv file.
In golang there is a inbuilt golang library like: encoding/csv which we are going to use in reading and writing csv file.
For writing over csv file, there are 2 methods provide from golang library first one is:
Write(record []string) : where slice of string is used to be one record of each field like column.
WriteAll(records [][]string) : in this scenario we store data in 2dminsional array or slice which represents each row and column for that csv file.
Flush(): this function is used to write those buffered data on the given csv file.
Implementation: for creating csv file first we need to create a file pointer and based on that file pointer csv file take that as a input and write all data on that file which file pointer mapped.
Code:
package main
import (
"encoding/csv"
"log"
"os"
)
func main() {
records := [][]string{
{"StudentName", "class-section", "age", "subject"},
{"xyz", "D", "22", "Math"},
{"sam", "E", "21", "Science"},
{"tom", "A", "23", "English"},
}
fp, err := os.Create("record.csv")
if nil != err {
log.Fatalf("Error : %s", err.Error())
}
w := csv.NewWriter(fp)
defer fp.Close()
defer w.Flush()
for _, studnetRecords := range records {
err = w.Write(studnetRecords)
if nil != err {
log.Fatalf("Write Err: %s", err.Error())
}
}
}
We successfully create a csv file in out local directory or given path.
In next post we are going to see how to read a csv file and also in upcoming post i am going to make some post like read csv file and generate chart based on those file data and also how to import data from csv file and insert those data into MySQL db.
0 Comments