我有一个CSV文件,想添加引号(")。
My CSV file:
comment_ID,comment_post_ID,product_SKU,comment_author,Comment
100,12505,B00E4MQODC,Elena, Nice Product
101,12505,B00E4MQODC,Jordan, Good Product
我想把它改成这样(每一列都有逗号):
comment_ID,comment_post_ID,product_SKU,comment_author,Comment
"100","12505","SD010E4MQODC","Elena", "Nice Product"
"101","12505","CB0E4MQ12ODC","Jordan", "Good Product"
我代码:
cwe := csv.NewWriter(cf)
cwe.Write([]string{"comment_ID", "comment_post_ID", "product_SKU", "comment_author", "comment"})
//Transfer Data To Comment CSV
for _, expose = range d {
var record []string
record = append(record, strconv.Itoa(int(cmtCounter)))
record = append(record, strconv.Itoa(exp.ID))
record = append(record, exp.SKU)
record = append(record, exp.review[zmcoun])
record = append(record, comment)
cwe.Write(record)
}
}
cwe.Flush()
我试了两种方法,但仍然不起作用:
`"`+variable+`"` //"""variable"""
Strings.Quote(variable) ///"""variable"""
我需要做同样的事情,并且std库中的csv写入器非常简单,只需修改几行即可完成我们想要的功能,如下所示。https://gist.github.com/andrea3bianchi/16d42a277db7b3de43b2a316b7894dbd
如果您将它与std库中的一个https://golang.org/src/encoding/csv/writer.go进行比较,您将看到我只添加了标志
ForceQuotes bool // True to add "" to every non-empty field
到主结构体和
if w.ForceQuotes {
return true
}
到fieldneedquotes函数
可以使用字符串格式
例如,您可以使用
而不是record = append(record, comment)
record = append(record, fmt.Sprintf("%v", comment))