How To Read CSV File in Golang

Reading and writing of file is a common functionality for web application. I am going to read CSV file and display data using golang .The 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.

The go programming language have "encoding/csv" package, this package help to read and write csv file in golang.I am using sample CSV file.

How To Read CSV file in Go

We will use NewReader method of csv package.This method help to read csv file in golang. Lets create 'csv_example' golang project into go workplace folder.The folder location would be d:/go_workplace/csv_example.

Create Sample CSV File

We will create a sample.csv file into d:/go_workplace/csv_example folder.This file contains following content in CSV format:

Read CSV File in GoLang

Let’s create a new main.go file and imported necessary package.

Now added logic to read csv file data and print into main() function –

First, we have opened the sample.csv file and stored into csv_file variable.The ferr variable have error message Like- if the file is not found.Then we have use csv.NewReader method to read data from csv file and stored reader into r variable.

Next, we will iterate line by line data using golang for loop. In the for loop , we are reading csv data line by line by r.Read() method. We are checking end of file using os.EOF method and break the read loop.

At the last line of the code , We are printing csv single record into console.

How To Run Go CSV file Read Example

Now, we will run above code using go run command –
d:/go_workplace/csv_example> go run main.go

You will see your csv data into console.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.