Skip to content

Instantly share code, notes, and snippets.

@hectorgool
Created August 24, 2017 22:21
Show Gist options
  • Save hectorgool/44d3c018c77d9b2b5ed5b4d7c16294df to your computer and use it in GitHub Desktop.
Save hectorgool/44d3c018c77d9b2b5ed5b4d7c16294df to your computer and use it in GitHub Desktop.
How to read a csv file in golang
/*
twitter@hector_gool
*/
package main
import (
"encoding/csv"
"fmt"
"os"
)
type Document struct {
colonia, ciudad, delegacion string
}
const (
FILE = "./MX.txt"
FILE_DELIMITER = '\t'
TOTAL_ROWS = 5
)
func main() {
file, err := os.Open(FILE)
printError(err)
defer file.Close()
reader := csv.NewReader(file)
reader.Comma = FILE_DELIMITER
rows, err := reader.ReadAll()
printError(err)
fmt.Printf("\nrows type: %T\n\n", rows)
d := new(Document)
for n, col := range rows {
d.colonia = col[2]
d.ciudad = col[3]
d.delegacion = col[5]
n++
if n <= TOTAL_ROWS {
fmt.Printf("%v,%v,%v;\n", d.colonia, d.ciudad, d.delegacion)
}
}
}
func printError(err error) {
if err != nil {
fmt.Printf("\nError: %v \n ", err.Error())
os.Exit(1)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment