douzhe9927 2018-11-11 04:43
浏览 233

使用ISO-8859-1编码在golang中解析CSV

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.

  • 写回答

2条回答 默认 最新

  • duanlei2150 2018-11-11 04:57
    关注

    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)
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向