Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
go
communitycreator

How to read CSV file in Go language

Shubham Singh Kshatriya

Go language provides a built-in package named encoding/csv for reading CSV files. In this shot, we will see how to use this package to read CSV data.

1. Create a CSV file

Let’s name this file data.csv.

Christiano Ronaldo, Portugal, 37
Lionel Messi, Argentina, 36
Neymar Jr, Brazil, 30

2. Create a golang file

Let’s name this file as main.go, and import the necessary packages.

package main

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

3. Open CSV file

We will use the os.Open() method to open the CSV file. This method accepts one parameter i.e. the file path, and returns the following:

  • fd: The file descriptor.
  • error: While opening the file, if some error is encountered, it will be stored in the error variable. If there are no errors, it will be nil.
fd, error := os.Open("data.csv")

if error != nil {
    fmt.Println(error)
}

fmt.Println("Successfully opened the CSV file")
defer file.Close()

After reading data from the file, we will close it in order to prevent a memory leak.

4. Read CSV file

We will use the csv.NewReader() method to read the CSV file and it will return a fileReader. To read the actual file content, we will use the ReadAll() method of fileReader.

fileReader:= csv.NewReader(fd)
records, error := fileReader.ReadAll()

if error != nil {
    fmt.Println(error)
}
 
fmt.Println(records)

Code

main.go
data.csv
package main

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

func main() {
  // open CSV file
  fd, error := os.Open("data.csv")
  if error != nil {
    fmt.Println(error)
  }
  fmt.Println("Successfully opened the CSV file")
  defer fd.Close()
    
  // read CSV file
  fileReader := csv.NewReader(fd)
  records, error := fileReader.ReadAll()
  if error != nil {
      fmt.Println(error)
  }
  fmt.Println(records)
}

As can be seen, we have opened and read the CSV file and then output the data on the console.

RELATED TAGS

golang
go
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring