我有一个csv文件,其中包含一行标题,然后是几十行。当我尝试将其读取为csv时,它会以1个大切片的形式返回。为什么不将其作为单独的行返回? 输入如下:
COL1,COL2
val1,val2
val1,val2
val1,val2
object.Body
是ReadCloser
lines, err := csv.NewReader(object.Body).ReadAll()
if err != nil {
log.Fatal(err)
}
for _, line := range lines {
log.Print(line)
}
输出返回为
[COL1 COL2
val1,val2
val1,val2
val1,val2]
我希望回报是:
[
[val1, val2],
[val1, val2],
[val1, val2],
]
有什么想法吗?完全陷入了这一困境。
编辑我错误地忘记在标题中添加逗号。这只是在示例代码中,而不是实际的问题。对困惑感到抱歉。
编辑,我相信此问题是由于csv文件的编码不同所致。
答案 0 :(得分:0)
我认为您提供的示例中的第一行格式不正确。应该不是COL1,COL2
吗?
我认为以下代码可以满足您的要求:
package main
import (
"bytes"
"encoding/csv"
"fmt"
)
func main() {
data := bytes.NewBufferString(`COL1,COL2
val1,val2
val1,val2
val1,val2`)
reader := csv.NewReader(data)
reader.Read() // Skip header
lines, err := reader.ReadAll()
if err != nil {
panic(err)
}
fmt.Println(lines)
}
答案 1 :(得分:0)
来自CSV RFC:
3. There maybe an optional header line appearing as the first line
of the file with the same format as normal record lines. This
header will contain names corresponding to the fields in the file
and should contain the same number of fields as the records in
the rest of the file (the presence or absence of the header line
should be indicated via the optional "header" parameter of this
MIME type). For example:
field_name,field_name,field_name CRLF
aaa,bbb,ccc CRLF
zzz,yyy,xxx CRLF
标头中缺少逗号,因此解析器认为整个文件只有一列宽。