在Golang中逐行读取csv/tsv文件并分割结果

问题描述 投票:0回答:1

我想在Golang中逐行读取一个TSV文件,并对一列数据进行处理。

这是我的数据:

酒吧 巴兹
1 2 10
2 3 50

这是一个非常适合我的目的的 C++ 代码:

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.
}

但是我找不到Go的类似代码。 这是在 Goland 中读取 tsv 的代码:

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])
}

结果将是:

1   2   10
2   3   50

但是我无法将每条记录拆分为 x, y, w。每行输出都是一个字符串,但我更喜欢一个列表,这样我可以轻松访问 w. (第三项)

csv go csvreader
1个回答
0
投票

如果我正确理解你的问题,你想要加载 csv,将其转换为嵌套数组,循环并访问嵌套数组上的 [2] 字段。我认为你已经非常接近了,但这是我使用的代码:

//file path of the master file
f, err := os.Open(filePath)
if err != nil {     
    log.Fatalf("ERROR: error opening file: %v", err)
}
defer f.Close()

//pass the file to the reader
r := csv.NewReader(f)   

recs, err := r.ReadAll()
if err != nil {fmt.Printf("Failed to readall issues: %s\n", err); return}

l := len(recs)

for i := 0; i < l; i++ {
  //Do something with the w field
  w := recs[i][2]
}
© www.soinside.com 2019 - 2024. All rights reserved.