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
What is risk management and why is it important?
Golang program to generate number of slices permutations of number entered by user
How to Convert string to integer type in Go?
Implementing Multiple Interfaces in Go Programming Language
How to remove multiple spaces in a string in GoLang?
Web Application to Get Trending Hashtags Near a Location