DEV Community

Santosh Anand
Santosh Anand

Posted on

2

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.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay