Read CSV with Go

Handwritten on 22 May 2019

How to read a CSV file in Go

File sample-data.csv:

id, name, age
1, Antony, 39
2, Amalia, 32
3, Tommy, 21
4, Andrew, 29
5, Kim, 24

File main.go:

package main

import (
    "bufio"
    "encoding/csv"
    "io"
    "log"
    "os"
)

func main() {
    csvFile, err := os.Open("sample-data.csv")
    if err != nil {
        log.Fatal("could not open csv file..")
    }
    reader := csv.NewReader(bufio.NewReader(csvFile))

    for {
        var line []string

        if line, err = reader.Read(); err != nil {
            if err == io.EOF {
                break
            }
            log.Fatal(err)
        }

        log.Printf("Hi, my name is %s and I am %s years old", line[1], line[2])
    }
}

Output:

2019/05/22 22:09:15 Hi, my name is  name and I am  age years old // header line
2019/05/22 22:09:15 Hi, my name is Antony and I am 39 years old
2019/05/22 22:09:15 Hi, my name is Amalia and I am 32 years old
2019/05/22 22:09:15 Hi, my name is Tommy and I am 21 years old
2019/05/22 22:09:15 Hi, my name is Andrew and I am 29 years old
2019/05/22 22:09:15 Hi, my name is Kim and I am 24 years old
Logo Adis.me

© 2024 Handcrafted in Nijmegen, The Netherlands