Fetching CSV data using Golang

Viewed 370

As you can see below I have read the CSV file and also fetched data using the index. After that, I aligned the header name with its respective index.

Now, how can I fetch particular data from the CSV file using the header name and not the index? I'm new to Golang and programming.

    func main() {
    file, ferr := os.Open("company1.csv")
    if ferr != nil {
    panic(ferr)
    }
    reader := csv.NewReader(file)
    reader.Comma = '|'
    reader.Comma = ','
    records, _ := reader.ReadAll()

    fmt.Println(records) // prints all the records
    fmt.Println("\n",records[1][0]) //to print the first record
    fmt.Println("\n",records[0]) // header
    //to print the index along the header
    index := 0
    for _, x := range records[0] {
    fmt.Println("\n",x ,"-",index)
    index++
    }
1 Answers

Create a map from header name to column index. Use that map when indexing a record:

fields := make(map[string]int)
for i, name := range records[0] {
    fields[name] = i
}

for _, record = range records[1:] {
    x = record[fields["name"]]
    fmt.Println(x)
}

The above code does not handle the case where an expected column is missing from the file. Add this check before looping through the data records:

for _, name := range []string{"name", "column2"} {
    if _, ok := fields[name]; !ok {
        log.Fatal("field missing", name)
    }
}
Related