2

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

1 Answer 1

6

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)
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you so much, but can u tell me how can I take the column name as user input, or make this process more dynamic.
There are many ways to get user input: command line flags, environment variables, read with the fmt or bufio package, etc. Once you the field name in a variable, let's call it field, you get that field from a record with record[fields[field].
@anvi, it looks like this is the answer for your question, please accept it so Penélope gets full credit.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.