首页  >  文章  >  后端开发  >  使用“encoding/csv”将带引号的字符串写入 CSV 文件时,为什么我的 Go 代码会产生额外的引号?

使用“encoding/csv”将带引号的字符串写入 CSV 文件时,为什么我的 Go 代码会产生额外的引号?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-26 20:17:29700浏览

Why does my Go code produce extra quotes when writing quoted strings to a CSV file using `encoding/csv`?

使用 Go 编码/CSV 的带引号字符串的奇怪 CSV 结果

在此代码片段中,目标是将数据写入 CSV 文件,确保带引号的字符串在数据已正确转义。但是,生成的 CSV 包含额外的引号,导致不一致。

<code class="go">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()
}</code>

带引号的字符串的预期输出为:

[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 阅读器会自动对它们进行转义。因此,解决方案是在写入带引号的字符串时删除多余的双引号。

修改代码

<code class="go">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)
}</code>

更新输出

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

通过此更改,带引号的字符串现在已正确转义,并删除了多余的引号。

以上是使用“encoding/csv”将带引号的字符串写入 CSV 文件时,为什么我的 Go 代码会产生额外的引号?的详细内容。更多信息请关注PHP中文网其他相关文章!

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