I have a csv file that has a row of headers and then several dozen lines. When I attempt to read it as a csv, it gets returned as 1 large slice. Why does it not get returned as separate rows? Input looks like:
COL1,COL2
val1,val2
val1,val2
val1,val2
object.Body
is a ReadCloser
lines, err := csv.NewReader(object.Body).ReadAll()
if err != nil {
log.Fatal(err)
}
for _, line := range lines {
log.Print(line)
}
Output is returned as
[COL1 COL2
val1,val2
val1,val2
val1,val2]
I would expect the return to be:
[
[val1, val2],
[val1, val2],
[val1, val2],
]
Any ideas? Totally stumped on this one.
Edit I mistakenly forgot to add a comma in the header. This was only in the sample code, not the actual issue. Sorry for the confusion.
Edit I believe that this issue is due to an encoding of the csv file differently.
I think the first row in the sample you provided is not formed correctly. Shouldn't it be COL1,COL2
instead?
I think the following code does what you want:
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)
}
From 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
You're missing a comma in the header, the parser therefore thinks that the whole file is one column wide.