parse a csv file in go

To parse a CSV file in Go, you need to use the encoding/csv package. This package provides a convenient way for reading and writing CSV files.

Here's an example of how to parse a CSV file in Go.

main.go
package main

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

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

    // Create a new CSV reader
    reader := csv.NewReader(file)

    // Read all rows from the CSV file
    rows, err := reader.ReadAll()
    if err != nil {
        fmt.Println("Error reading CSV file:", err)
        return
    }

    // Print out the rows
    for _, row := range rows {
        for _, column := range row {
            fmt.Printf("%s ", column)
        }
        fmt.Println()
    }
}
658 chars
36 lines

In this example, we first open the CSV file using the os.Open() function. If an error occurs, we print an error message and return. We defer the file's closure until the end of the function.

Next, we create a new csv.Reader using the opened file. We then call the ReadAll() function to read all rows from the CSV file. If an error occurs, we again print an error message and return.

Finally, we iterate over all rows and columns of the CSV file and print them out to the console.

gistlibby LogSnag