Parsing comma-separated data

Create a file named data.csv with the following content:

"Name","Surname","Age"
# this is comment in data
"sangam","biradar",24
arjun,singh,21

Create the main.go file with the following content:


        package main

        import (
          "encoding/csv"
          "fmt"
          "os"
        )

        func main() {

          file, err := os.Open("data.csv")
          if err != nil {
            panic(err)
          }
          defer file.Close()

          reader := csv.NewReader(file)
          reader.FieldsPerRecord = 3
          reader.Comment = '#'

          for {
            record, e := reader.Read()
            if e != nil {
              fmt.Println(e)
              break
            }
            fmt.Println(record)
          }
        }

output:

sangam:golang-daily sangam$ go run main.go
[Name Surname Age]
[sangam biradar 24]
[arjun singh 21]
EOF
sangam:golang-daily sangam$ 

Create a file named data_uncommon.csv with the following content:

Name;Surname;Age
"sangam";biradar;24
"arjun";singh;21


Create a file named main.go with the following content:

package main

import (
	"encoding/csv"
	"fmt"
	"os"
)

func main() {

	file, err := os.Open("data_uncommon.csv")
	if err != nil {
		panic(err)
	}
	defer file.Close()

	reader := csv.NewReader(file)
	reader.Comma = ';'

	for {
		record, e := reader.Read()
		if e != nil {
			fmt.Println(e)
			break
		}
		fmt.Println(record)
	}
}


output:

sangam:golang-daily sangam$ go run main.go
[Name Surname Age]
[sangam biradar 24]
[arjun singh 21]
EOF
sangam:golang-daily sangam$ 

How it works…