Skip to content

Instantly share code, notes, and snippets.

@cskonopka
Created May 6, 2019 18:06
Show Gist options
  • Save cskonopka/4cdbb217d9eb25c40acfc9112c2356dc to your computer and use it in GitHub Desktop.
Save cskonopka/4cdbb217d9eb25c40acfc9112c2356dc to your computer and use it in GitHub Desktop.
Basic example how to read a CSV file and add it's contents to a new data object in Go.
package main
import (
"encoding/csv"
"fmt"
"os"
)
type CsvLine struct {
Column1 string
Column2 string
Column3 string
}
func main() {
// Link CSV file
filename := "CSV_FILE"
// Open CSV file
f, err := os.Open(filename)
if err != nil {
panic(err)
}
defer f.Close()
// Read File into *lines* variable
lines, err := csv.NewReader(f).ReadAll()
if err != nil {
panic(err)
}
// Loop through *lines*, create data object, each piece to their respective column
for _, line := range lines {
data := CsvLine{
Column1: line[0],
Column2: line[1],
Column3: line[2],
}
fmt.Println(data.Column1 + " " + data.Column2 + " " + data.Column3)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment