Home > other >  How to return an array from reading a file?
How to return an array from reading a file?

Time:01-16

I have two columns in a CSV file. I am accessing only the first column using the SearchData() function.

The problem is that I want to access the data as an array but when I return an array string in the AccessData() function and write the products[0] in the SearchData(), it gives me all the data by removing the bracket sign [] only and when I write products[1], it gives me runtime error: index out of range [1] with length 1.

Required result

products[0] = First Item
products[1] = Second Item
...
so on

Code

func AccessData(number int) string {
    content, err := ioutil.ReadFile("products/data1.csv")
    if err != nil {
        log.Fatal(err)
    }
    Data := string(content)
    sliceData := strings.Split(Data, ",")
    return sliceData[number]
}

func SearchData(){
    for i := 0; i <= 34; i = i   2 {
        products := AccessData(i)
        fmt.Println(products)
    }
}

CodePudding user response:

This should do the trick:

func firstColumns(filename string) []string {
    f, err := os.Open(filename)
    if err != nil {
        log.Fatal(err)
    }
    defer f.Close()

    r := csv.NewReader(f)

    var result []string
    for {
        row, err := r.Read()
        if err != nil {
            if err == io.EOF {
                break
            }

            log.Fatal(err)
        }

        if len(row) > 0 {
            result = append(result, row[0])
        }
    }

    return result
}

func main() {
    data := firstColumns("products/data1.csv")
    fmt.Println(data)
    fmt.Println(data[1])
}

This turns the the first column of every row into a []string which can be access index.

The output is:

[First item Second item]
Second item
  •  Tags:  
  • Related