Read csv file using Golang

RMAG news

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(“%st, col)
}
fmt.Println()
}
}

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.

Leave a Reply

Your email address will not be published. Required fields are marked *