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 do you handle HTTP client server logging in Go?
How to remove special characters from a string in GoLang?
How to create Slice of Struct in Golang?
Go program to find CNAME record of a domain
Golang program for implementation of Knuth–Morris–Pratt (KMP) Algorithm
What is the default HTTP server in Go?