Dec 232019

ADM

How to read CSV file in Golang

  • December 23 2019
  • ADM

 

 

How to read CSV file in Golang - golang

 

CSV is a highly used data language, commonly to Excel and spreadsheets. It is easy to used when data is transported between different systems.

File

For this example we took an simple example of a CSV file containing three columns name, address and phone. Exactly as in How to write CSV file in Golang.

Name,Address,Phone
Deidre Haider,"631 Grand Avenue Glendora, CA 91740",202-555-0150
Annette Sharrock,"230 Railroad Avenue Myrtle Beach, SC 29577",202-555-0149
Ebonie Skowron,"762 Deerfield Drive Romeoville, IL 60446",202-555-0155
Devon Huynh,"573 Hudson Street Wooster, OH 44691",202-555-0196
Cristine Riddle,"858 2nd Avenue Prior Lake, MN 55372",202-555-0182
Kristeen Ellman,"169 Creekside Drive Front Royal, VA 22630",202-555-0198
Ocie Blansett,"8 Grant Street Dracut, MA 01826",202-555-0135
Ami Feucht,"783 4th Street Leland, NC 28451",202-555-0105
Elroy Geers,"856 Grant Avenue Richmond, VA 23223",202-555-0134
Shaunte Brockwell,"1000 Park Place Mooresville, NC 28115",202-555-0140
Evonne Kellar,"309 Briarwood Drive Stow, OH 44224",202-555-0155
Gladis Schwalb,"407 13th Street Hobart, IN 46342",202-555-0109
Terina Fukuda,"25 Primrose Lane High Point, NC 27265",202-555-0151
Annetta Knicely,"647 Fieldstone Drive Dalton, GA 30721",202-555-0187
Rozanne Westmoreland,"36 9th Street West Voorhees, NJ 08043",202-555-0156
Louella Hutchens,"63 Route 41 Helotes, TX 78023",202-555-0113
Alesha Ennis,"505 Bank Street Morganton, NC 28655",202-555-0133
Carisa Motton,"114 Orchard Avenue Fort Mill, SC 29708",202-555-0153
Zane Gard,"678 Spruce Avenue Milford, MA 01757",202-555-0124
Marya Patchett,"868 2nd Street Canonsburg, PA 15317",202-555-0189

Code

package main

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

type Record struct {
	Name    string
	Address string
	Phone   string
}

func main() {
	fmt.Println("Reading CSV file using Golang")
	fmt.Println()
	csvFile, err := os.Open("data.csv")
	if err != nil {
		fmt.Println("Cannot open file", err)
	}
	defer csvFile.Close()

	//read data into multi-dimentional array of strings
	csvLines, err := csv.NewReader(csvFile).ReadAll()
	if err != nil {
		fmt.Println(err)
	}

	//convert the multi-dimentional array of strings into an array of struct
	var data []Record
	for _, line := range csvLines {
		row := Record{
			Name:    line[0],
			Address: line[1],
			Phone:   line[2],
		}
		data = append(data, row)
	}

	// Loop through the array of struct and display the result
	for _, row := range data {
		fmt.Println(row.Name + " \t\t " + row.Address + " \t\t " + row.Phone)
	}
}

Output

Reading CSV file using Golang

Name             Address                 Phone
Deidre Haider            631 Grand Avenue Glendora, CA 91740             202-555-0150
Annette Sharrock                 230 Railroad Avenue Myrtle Beach, SC 29577              202-555-0149
Ebonie Skowron           762 Deerfield Drive Romeoville, IL 60446                202-555-0155
Devon Huynh              573 Hudson Street Wooster, OH 44691             202-555-0196
Cristine Riddle                  858 2nd Avenue Prior Lake, MN 55372             202-555-0182
Kristeen Ellman                  169 Creekside Drive Front Royal, VA 22630               202-555-0198
Ocie Blansett            8 Grant Street Dracut, MA 01826                 202-555-0135
Ami Feucht               783 4th Street Leland, NC 28451                 202-555-0105
Elroy Geers              856 Grant Avenue Richmond, VA 23223             202-555-0134
Shaunte Brockwell                1000 Park Place Mooresville, NC 28115           202-555-0140
Evonne Kellar            309 Briarwood Drive Stow, OH 44224              202-555-0155
Gladis Schwalb           407 13th Street Hobart, IN 46342                202-555-0109
Terina Fukuda            25 Primrose Lane High Point, NC 27265           202-555-0151
Annetta Knicely                  647 Fieldstone Drive Dalton, GA 30721           202-555-0187
Rozanne Westmoreland             36 9th Street West Voorhees, NJ 08043           202-555-0156
Louella Hutchens                 63 Route 41 Helotes, TX 78023           202-555-0113
Alesha Ennis             505 Bank Street Morganton, NC 28655             202-555-0133
Carisa Motton            114 Orchard Avenue Fort Mill, SC 29708                  202-555-0153
Zane Gard                678 Spruce Avenue Milford, MA 01757             202-555-0124
Marya Patchett           868 2nd Street Canonsburg, PA 15317             202-555-0189

Compile&Run

To compile the code navigate to the file location and run the following command.

$ go build readCSV.go

Assuming that readCSV.go is the name of your file.

Then depending on if you are on Linux or Windows the binary file is created.

To run the application execute the command.

Linux

$ ./readCSV

Windows

c:\Users\adm\go\tutorials> readCSV.exe

If you want to compile and run the application in one single step run the following command:

go run readCSV.go

References