Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

How to read CSV file in Golang

This Golang tutorial help to read csv file and printout records into console. CSV(comma separated value) is very common format to share data,You can easily generate csv file using Google Sheets, Microsoft Excel and RDBMS applications.

This Golang Tutorial implements how to read CSV file and printed within the application.

To read csv data in golang is very easy, The Golang is providing, encoding/csv package that help to CSV related operation.I am using sample CSV file, that has following content in CSV format:

Start Date ,Start Time,End Date,End Time,Event Title ,All Day Event,No End Time,Event Description,Contact ,Contact Email,Contact Phone,Location,Category,Mandatory,Registration,Maximum,Last Date To Register
9/5/2011,3:00:00 PM,9/5/2011,,Social Studies Dept. Meeting,N,Y,Department meeting,Chris Gallagher,[email protected],814-555-5179,High School,2,N,N,25,9/2/2011
9/5/2011,6:00:00 PM,9/5/2011,8:00:00 PM,Curriculum Meeting,N,N,Curriculum Meeting,Chris Gallagher,[email protected],814-555-5179,High School,2,N,N,25,9/2/2011

I created sample.csv file and stored above data into this file.I also create main.go file that will have all go logic to read CSV file.

package main

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

func main() {
	csv_file, _ := os.Open("sample.csv")
	r := csv.NewReader(csv_file)

	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}
		if err != nil {
			log.Fatal(err)
		}

		fmt.Println(record)
	}
}

I can assume, Both the files should exist at the same location on the computer.

The post How to read CSV file in Golang appeared first on Rest Api Example.



This post first appeared on Rest Api Example, please read the originial post: here

Share the post

How to read CSV file in Golang

×

Subscribe to Rest Api Example

Get updates delivered right to your inbox!

Thank you for your subscription

×