Golang read csv file into struct
The csv package have a
NewReader()
function which returns a Reader
object to process CSV data. A csv.Reader
converts \r\n sequences in its input to just \n, which includes multi line field values also.
Example
package main
import (
"bufio"
"fmt"
"log"
"os"
)
func main() {
file, err := os.Open("test.txt")
if err != nil {
log.Fatalf("failed opening file: %s", err)
}
scanner := bufio.NewScanner(file)
scanner.Split(bufio.ScanLines)
var txtlines []string
for scanner.Scan() {
txtlines = append(txtlines, scanner.Text())
}
file.Close()
for _, eachline := range txtlines {
fmt.Println(eachline)
}
}
Output
Name -- City -- Job
John -- London -- CA
Micky -- Paris -- IT
os.Open()
function, which returns an pointer type instance of os.File
. The csv.Reader.Read()
method is used to decode each file record into pre-defined struct CSVData
and then store them in a slice until io.EOF
is returned.
Most Helpful This Week
How to convert Struct fields into Map String?
GO Program to Generate Multiplication Table
Golang program for implementation of Insertion Sort
Go program to find MX records record of a domain
Golang program for implementation of Tower of Hanoi Algorithm
Top Programming Languages Behind Blockchain App Development
How do you handle HTTP client server compression in Go?
GO Program to find area and circumference of circle
Invalid memory address or nil pointer dereference error in Golang
Convert Int data type to Int16 Int32 Int64