string - go encoding/csv 中引用字符串的奇怪 CSV 结果

标签 string csv escaping go

我有一小段代码让我整个周末都很忙。

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/

相关文章:

c - 如何将字符串拆分一次?

ruby - 根据长度读取行

c# - 日期时间.ToString()?

url - 为什么 url.Parse 不填充 URL.RawPath?

python - 使用 json.dumps 将 UTF-8 文本保存为 UTF-8,而不是\u 转义序列

c++ - 将字符串重新排序为没有连续相同字符的字符串

结构中的 C malloc

csv - 逗号分隔值.csv格式的一个字段的多个值

Python 多核 CSV 短程序,需要建议/帮助

JavaScript 转义序列