在此代码片段中,目标是将数据写入 CSV 文件,确保引用的字符串在数据已正确转义。但是,生成的 CSV 包含额外的引号,导致不一致。
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
f, err := os.Create("test.csv")
if err != nil {
log.Fatal(err)
}
defer f.Close()
w := csv.NewWriter(f)
record := []string{"Unquoted string", "Cr@zy text with , and \\ and \" etc"}
w.Write(record)
record = []string{"Quoted string", fmt.Sprintf("%q", "Cr@zy text with , and \\ and \" etc")}
w.Write(record)
w.Flush()
}
带引号的字符串的预期输出为:
[Unquoted string Cr@zy text with , and \ and " etc] [Quoted string "Cr@zy text with , and \\ and \" etc"]
但是,实际输出包含额外的引号:
Unquoted string,"Cr@zy text with , and \ and "" etc" Quoted string,"""Cr@zy text with , and \\ and \"" etc"""
理解额外引号
带引号的字符串是遵循 CSV 标准的结果,该标准要求将双引号转义为两个双引号。这是区分数据中实际双引号和用于记录分隔的双引号所必需的。
解决方案
代码不需要担心转义双引号,因为CSV 阅读器会自动对它们进行转义。因此解决办法就是在写带引号的字符串时去掉多余的双引号。
修改代码
for _, record := range [][]string{
{"Unquoted string", "Cr@zy text with , and \\ and \" etc"},
{"Quoted string", "Cr@zy text with , and \\ and \" etc"},
} {
record[1] = fmt.Sprintf("%q", record[1][1:len(record[1])-1])
w.Write(record)
}
更新输出
Unquoted string,Cr@zy text with , and \ and " etc Quoted string,"Cr@zy text with , and \\ and \" etc"
通过此更改,带引号的字符串现在已正确转义,并且删除了多余的引号。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3