使用ISO-8859-1编码在golang中解析CSV [英] Parsing CSV in golang with ISO-8859-1 encoding
问题描述
我有一个csv文件,其中包含一行标题,然后是几十行.当我尝试将其读取为csv时,它会以1个大切片的形式返回.为什么不将其作为单独的行返回? 输入如下:
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
是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],
]
有什么想法吗?完全陷入了这一困境.
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.
编辑,我认为此问题是由于csv文件的编码不同所致.
Edit I believe that this issue is due to an encoding of the csv file differently.
推荐答案
来自 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.
这篇关于使用ISO-8859-1编码在golang中解析CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!