How to read values from CSV file in Golang 1.20
In this video we are going to generate source code for the GoLang Program, How to read values from CSV file using chatGPT.
After generating we will verify and run the generated code.
IMPORTANT NOTE on SOURCE CODE: only source code that are acceptable by the youtube description box will be displayed.
##############SOURCE CODE#########################
package main
import (
"encoding/csv"
"fmt"
"os"
)
func main() {
// Open the CSV file
file, err := os.Open("data.csv")
if err != nil {
panic(err)
}
defer file.Close()
// Create a new CSV reader
reader := csv.NewReader(file)
// Read all the CSV records
records, err := reader.ReadAll()
if err != nil {
panic(err)
}
// Print each record
for _, record := range records {
fmt.Println(record)
}
}
##############END OF SOURCE CODE#########################
Below is the explanation for the program:
The program first opens the CSV file using the os.Open() function. It then creates a new CSV reader using the csv.NewReader() function and passes the file to it. The csv package automatically handles parsing the CSV file according to the default delimiter (a comma) and returns a slice of slices, where each inner slice represents a row in the CSV file.
The ReadAll() function is then called on the CSV reader to read all the CSV records at once. This function returns a slice of slices, where each inner slice represents a row in the CSV file. If there is an error while reading the CSV file, the program will panic.
Finally, the program prints each record using a for loop and fmt.Println().
#go #goprogramming #golang #golangtutorial #golanguage