dongwen6743 2017-11-27 18:11
浏览 219
已采纳

将地图写入CSV

I've been attempting to figure out how to properly write a map to a csv file with no luck.

I essentially have a program that queries an sql database, I store one of the return values as the key to the map, and then a slice of string for the data related to it that's returned, as an example the map would be:

var m = make(map[string][]string)

m['test1'] = [5, 4, 3]

so writing it to a csv would be

test1, 5, 4, 3

Its printed to the csv just like a list/slice would be, I'm storing it in a map to make it easier to construct dynamic queries elsewhere.

I've attempted using a for loop such that:

for key, value := range m{
    writer.Write(key)
    writer.Write(value)
}

but I'm getting the following error:

cannot use key (type string) as type []string in argument to writer.Write

I've done a lot of googling and searching here and can't seem to find a way to do this properly.

  • 写回答

1条回答 默认 最新

  • douyan1921 2017-11-27 18:48
    关注

    Package csv

    func (*Writer) Write

    func (w *Writer) Write(record []string) error
    

    Writer writes a single CSV record to w along with any necessary quoting. A record is a slice of strings with each string being one field.


    error: cannot use key (type string) as type []string in argument to writer.Write


    "I've done a lot of googling and searching here."

    To solve this problem, read the documentation of Write and follow the instructions in the error message, You have type string, Write wants type []string. For example,

    for key, value := range m {
        r := make([]string, 0, 1+len(value))
        r = append(r, key)
        r = append(r, value...)
        err := writer.Write(r)
        if err != nil {
            // handle error
        }
    }
    writer.Flush()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 交替优化波束形成和ris反射角使保密速率最大化
  • ¥15 树莓派与pix飞控通信
  • ¥15 自动转发微信群信息到另外一个微信群
  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程