Created
May 6, 2019 18:06
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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