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()
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)