Golang ProgramsGolang Programs

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.
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)
	}
}
 

The file test.csv have few records is opened in read-only mode using the 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.

C:\golang\file>go run example6.go
Name -- City -- Job
John -- London -- CA
Micky -- Paris -- IT

C:\golang\file>