Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading CSV file in Go

Tags:

go

Here is a code snippet that reads CSV file:

func parseLocation(file string) (map[string]Point, error) {     f, err := os.Open(file)     defer f.Close()     if err != nil {         return nil, err     }     lines, err := csv.NewReader(f).ReadAll()     if err != nil {         return nil, err     }     locations := make(map[string]Point)     for _, line := range lines {         name := line[0]         lat, laterr := strconv.ParseFloat(line[1], 64)         if laterr != nil {             return nil, laterr         }         lon, lonerr := strconv.ParseFloat(line[2], 64)         if lonerr != nil {             return nil, lonerr         }         locations[name] = Point{lat, lon}     }     return locations, nil } 

Is there a way to improve readability of this code? if and nil noise.

like image 915
Lukasz Madon Avatar asked Jul 28 '14 15:07

Lukasz Madon


People also ask

What is CSV file format?

A CSV is a comma-separated values file, which allows data to be saved in a tabular format. CSVs look like a garden-variety spreadsheet but with a . csv extension. CSV files can be used with most any spreadsheet program, such as Microsoft Excel or Google Spreadsheets.


1 Answers

Go now has a csv package for this. Its is encoding/csv. You can find the docs here: https://golang.org/pkg/encoding/csv/

There are a couple of good examples in the docs. Here is a helper method I created to read a csv file and returns its records.

package main  import (     "encoding/csv"     "fmt"     "log"     "os" )  func readCsvFile(filePath string) [][]string {     f, err := os.Open(filePath)     if err != nil {         log.Fatal("Unable to read input file " + filePath, err)     }     defer f.Close()      csvReader := csv.NewReader(f)     records, err := csvReader.ReadAll()     if err != nil {         log.Fatal("Unable to parse file as CSV for " + filePath, err)     }      return records }  func main() {     records := readCsvFile("../tasks.csv")     fmt.Println(records) } 
like image 95
SyntaxRules Avatar answered Sep 20 '22 14:09

SyntaxRules