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.
Let’s name this file data.csv
.
Christiano Ronaldo, Portugal, 37
Lionel Messi, Argentina, 36
Neymar Jr, Brazil, 30
Let’s name this file as main.go
and import the necessary packages.
package main
import (
"encoding/csv"
"fmt"
"os"
)
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.
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)
package mainimport ("encoding/csv""fmt""os")func main() {// open CSV filefd, error := os.Open("data.csv")if error != nil {fmt.Println(error)}fmt.Println("Successfully opened the CSV file")defer fd.Close()// read CSV filefileReader := 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