我有一小段代码让我整个周末都很忙。
package main
import (
"encoding/csv"
"fmt"
"log"
"os"
)
func main() {
f, err := os.Create("./test.csv")
if err != nil {
log.Fatal("Error: %s", err)
}
defer f.Close()
w := csv.NewWriter(f)
var record []string
record = append(record, "Unquoted string")
s := "Cr@zy text with , and \\ and \" etc"
record = append(record, s)
fmt.Println(record)
w.Write(record)
record = make([]string, 0)
record = append(record, "Quoted string")
s = fmt.Sprintf("%q", s)
record = append(record, s)
fmt.Println(record)
w.Write(record)
w.Flush()
}
运行时打印出:
[Unquoted string Cr@zy text with , and \ and " etc]
[Quoted string "Cr@zy text with , and \\ and \" etc"]
第二个引用的文本正是我希望在 CSV 中看到的内容,但我得到的是:
Unquoted string,"Cr@zy text with , and \ and "" etc"
Quoted string,"""Cr@zy text with , and \\ and \"" etc"""
那些额外的引语从何而来,我该如何避免它们? 我已经尝试了很多东西,包括使用 strings.Quote 等等,但我似乎找不到完美的解决方案。帮忙,好吗?
最佳答案
它是将数据存储为 CSV 的标准的一部分。 出于解析原因,需要对双引号字符进行转义。
A (double) quote character in a field must be represented by two (double) quote characters.
发件人:http://en.wikipedia.org/wiki/Comma-separated_values
您真的不必担心,因为 CSV 阅读器会取消转义双引号。
示例:
package main
import (
"encoding/csv"
"fmt"
"os"
)
func checkError(e error){
if e != nil {
panic(e)
}
}
func writeCSV(){
fmt.Println("Writing csv")
f, err := os.Create("./test.csv")
checkError(err)
defer f.Close()
w := csv.NewWriter(f)
s := "Cr@zy text with , and \\ and \" etc"
record := []string{
"Unquoted string",
s,
}
fmt.Println(record)
w.Write(record)
record = []string{
"Quoted string",
fmt.Sprintf("%q",s),
}
fmt.Println(record)
w.Write(record)
w.Flush()
}
func readCSV(){
fmt.Println("Reading csv")
file, err := os.Open("./test.csv")
defer file.Close();
cr := csv.NewReader(file)
records, err := cr.ReadAll()
checkError(err)
for _, record := range records {
fmt.Println(record)
}
}
func main() {
writeCSV()
readCSV()
}
输出
Writing csv
[Unquoted string Cr@zy text with , and \ and " etc]
[Quoted string "Cr@zy text with , and \\ and \" etc"]
Reading csv
[Unquoted string Cr@zy text with , and \ and " etc]
[Quoted string "Cr@zy text with , and \\ and \" etc"]
这是写函数的代码。 func (w *Writer) Write(record []string) (err error)
关于string - go encoding/csv 中引用字符串的奇怪 CSV 结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20459038/