首頁  >  文章  >  後端開發  >  使用“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