首页  >  文章  >  后端开发  >  如何使用 Go 的 `encoding/csv` 包处理 CSV 编码中带引号的字符串?

如何使用 Go 的 `encoding/csv` 包处理 CSV 编码中带引号的字符串?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-27 09:13:30949浏览

How do you handle quoted strings in CSV encoding with Go's `encoding/csv` package?

Go中的CSV编码:处理带引号的字符串

在Go的encoding/csv包中,处理带引号的字符串有时会导致意想不到的结果。编写 CSV 记录时,了解编码特殊字符(例如双引号)的标准要求至关重要。

根据 CSV 规范,字段中的双引号字符必须使用第二个双引号字符进行转义。出于解析原因,此转义序列是必需的。

示例:

<code class="go">import "encoding/csv"

record := []string{
    "Unquoted string",
    "Cr@zy text with , and \ and \" etc",
}

writer := csv.NewWriter(writer)
writer.Write(record)</code>

上面的代码将写入一个带有双引号转义的字符串:

<code class="csv">Unquoted string
"Cr@zy text with , and \ and \" etc"</code>

避免额外引号:

要避免在读取 CSV 文件时插入额外引号,应采取以下步骤:

  • 写入时带引号的字符串,使用 fmt.Sprintf("%q", string) 正确转义双引号。
  • 读取带引号的字符串时,CSV 阅读器会自动取消双引号转义,确保获取原始字符串.

代码示例:

<code class="go">func writeCSV() {
    writer := csv.NewWriter(writer)
    s := "Cr@zy text with , and \ and \" etc"

    record := []string{
        "Unquoted string",
        "Quoted string",
        fmt.Sprintf("%q", s),
    }

    writer.Write(record)
}

func readCSV() {
    reader := csv.NewReader(reader)
    records, err := reader.ReadAll()

    for _, record := range records {
        // Printed records automatically have double quotes unescaped by the CSV reader.
        fmt.Println(record)
    }
}</code>

输出:

[Unquoted string Cr@zy text with , and \ and " etc]
[Quoted string Cr@zy text with , and \ and " etc]

以上是如何使用 Go 的 `encoding/csv` 包处理 CSV 编码中带引号的字符串?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn