read a csv file in go

To read a CSV file in Go, we will first need to import the "encoding/csv" package. The following code snippet demonstrates how to read a CSV file:

main.go
package main

import (
    "encoding/csv"
    "fmt"
    "os"
)

func main() {
    // Open the CSV file
    csvfile, err := os.Open("data.csv")
    if err != nil {
        fmt.Println(err)
        return
    }

    // Parse the file
    r := csv.NewReader(csvfile)

    // Iterate through the records
    for {
        record, err := r.Read()

        // Stop at EOF
        if err == csv.ErrRecordNotFound || err == io.EOF {
            break
        }

        // Handle errors
        if err != nil {
            fmt.Println(err)
            return
        }

        // Print the record
        fmt.Println(record)
    }

    // Close the file
    csvfile.Close()
}
669 chars
42 lines

In this code, we first open the CSV file using os.Open(). We then create a new csv.Reader using the opened file. We can then iterate through the records in the file using r.Read(), which returns a slice of strings representing each record in the CSV file.

We also check for any errors while reading the CSV file, and we close the file when we are finished reading it.

related categories

gistlibby LogSnag