How to read a CSV file in the Go language

The 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: If an 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 fd.Close()

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

4. Read CSV file

We use the csv.NewReader() method to read the CSV file and returns 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 open the CSV file, read it, and then output the data on the console.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved