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 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题