DEV Community

Santosh Anand
Santosh Anand

Posted on

Read csv file using Golang

To read a CSV file in Go, you can use the encoding/csv package, which provides functionalities to handle CSV files. Here's a basic example of how you can read a CSV file in 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:", err)
        return
    }
    defer file.Close()

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

    // Read the CSV records
    records, err := reader.ReadAll()
    if err != nil {
        fmt.Println("Error:", err)
        return
    }

    // Print the CSV data
    for _, row := range records {
        for _, col := range row {
            fmt.Printf("%s\t", col)
        }
        fmt.Println()
    }
}

Enter fullscreen mode Exit fullscreen mode

In this example:

We open the CSV file using os.Open().
We create a new CSV reader using csv.NewReader().
We use ReadAll() to read all the records from the CSV file into a slice of slices.
We iterate over each row and column in the CSV data and print it to the console.
Ensure that you replace "data.csv" with the actual path to your CSV file. Additionally, handle errors appropriately based on your application's requirements.

Top comments (0)