📚Cheatsheets

Cheatsheet collection for go, rust, python, shell and javascript.

How to read csv in Golang?

To read a CSV file in Golang, you can use the encoding/csv package in the standard library. Here's an example of how you can use this package to read a CSV file and print its contents to the console:

package main

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

func main() {
    // Open the CSV file.
    file, err := os.Open("test.csv")
    if err != nil {
        panic(err)
    }
    defer file.Close()

    // Read the CSV file.
    reader := csv.NewReader(file)
    records, err := reader.ReadAll()
    if err != nil {
        panic(err)
    }

    // Print the contents of the CSV file.
    for _, record := range records {
        fmt.Println(record)
    }
}

The csv.NewReader function creates a new CSV reader, which is used to read the records in the CSV file. The reader.ReadAll method reads all the records in the file and returns them as a two-dimensional slice of strings. Finally, the records are iterated over and printed to the console.

This is just a simple example of how to read a CSV file in Golang. You can customize the code to fit your specific needs. For example, you can specify the delimiter character to use, or you can use the csv.Reader.Read method to read the records one at a time instead of reading all of them at once.