douou6696 2018-05-19 03:22
浏览 278
已采纳

Golang编写CSV的新列

I'm writing out two sets of data to one CSV in Go. Right now, using csv.NewWriter, I can write them to the same columns. This is not ideal, I would like them side-by-side, the second dataset in adjacent columns. Here's what I'm doing now:

    csvOut, _ := os.Create("Summary.csv")
    writer := csv.NewWriter(csvOut)

    for _, value := range dataset1 {
            writer.Write(value)
    }
    writer.Flush()
    for _, value := range dataset2 {
            writer.Write(value)
    }
    writer.Flush()

I know the normal writer has some offset options, does the csv writer have anything similar?

  • 写回答

1条回答 默认 最新

  • dptn69182 2018-05-19 03:58
    关注

    Loop over the source data set records. Concatenate the records from each data set to create an output record. Write the output record to the file.

    csvOut, _ := os.Create("Summary.csv")
    writer := csv.NewWriter(csvOut)
    
    var record []string  // declare record outside loop to reduce allocations
    for i := range dataset1 {
            record = append(record[:0], dataset1[i]...) // copy data set 1 to beginning of output record
            record = append(record, dataset2[i]...) // append data set 2 to output record
            writer.Write(record)
    }
    writer.Flush()
    

    This code assumes that len(dataset1) == len(dataset2). If this is not true, then modify the code per application requirements (add empty values, truncate to shorter dataset, ...)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题