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
: 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.
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)
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
CONTRIBUTOR
View all Courses