I want to read a TSV file in Golang, line by line, and do a process on a column of data.
Here is what my data looks like:
| foo | bar | baz |
|---|---|---|
| 1 | 2 | 10 |
| 2 | 3 | 50 |
Here is a C++ code that works well for my purpose:
ifstream iFile("input.tsv");
iFile >> str >> str >> str; // Skip first line
int sum = 0;
while (iFile >> x >> y >> w)
{
sum += w; // A simple process on the third column.
}
But I can't find a similar code for Go. Here is a code for reading tsv in Goland:
file, _ := os.Open("input.tsv")
defer file.Close()
csvReader := csv.NewReader(file)
csvReader.Comma = '\t'
for {
rec, err := csvReader.Read()
fmt.Printf("%+v\n", rec[0])
}
The result will be:
1 2 10
2 3 50
But I can't split each record into x, y, w. Each line of output is a string but I prefer a list so I can easily access w. (the third item)
P.S.: The problem is solved. As @JimB showed us HERE, the code is working.
When the tsv file format is correct, the result will be
[]string{"1", "2", "10"}
[]string{"2", "3", "50"}
but if the tsv file uses multiple spaces instead of a tab, the result will be:
[]string{"1 2 100"}
[]string{"2 3 50"}
Which is not what we want.
If I understand your question correctly, you want to load the csv, turn it into a nested array, loop through and access the [2] field on the nested array. I think you're already pretty close, but this is the code I've used:
As mentioned, you can read each line by using a callback in gocsv. I usually don't do this and simply marshal the file and then read but this is how I would do it if I did do it line by line:
Using a file such as:
However, I usually use gocsv to marshal the file at one time in this manner: