[Go] Read a CSV file
Created on November 29, 2026
You can use the encoding/csv package to read a CSV file. This example reads names and ages from dummy_users.csv and stores each record in a User struct.
"Tom",20
"Bob",10
"Alice",15
package main
import (
"encoding/csv"
"fmt"
"io"
"os"
"strconv"
)
type User struct {
Name string
Age int
}
func main() {
file, err := os.Open("dummy_users.csv")
if err != nil {
panic(err)
}
defer file.Close()
reader := csv.NewReader(file)
reader.FieldsPerRecord = 2
users := []User{}
for {
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
panic(err)
}
age, err := strconv.Atoi(record[1])
if err != nil {
continue
}
users = append(users, User{Name: record[0], Age: age})
}
fmt.Println(users)
}
os.Open()opens the file.csv.NewReader()creates a reader for it, andFieldsPerRecordrequires two columns in each record.reader.Read()returns one record as a slice of strings.io.EOFmarks the end of the file. Other read errors stop the program.strconv.Atoi()converts the second field to an integer. The example skips records whose age cannot be converted and appends each remaining record tousers.
The program prints:
[{Tom 20} {Bob 10} {Alice 15}]