首頁  >  文章  >  後端開發  >  為什麼 Go 的 `encoding/csv` 套件會向 CSV 檔案中的參考字串添加額外的引號?

為什麼 Go 的 `encoding/csv` 套件會向 CSV 檔案中的參考字串添加額外的引號?

Barbara Streisand
Barbara Streisand原創
2024-10-25 04:09:02473瀏覽

Why Does Go's `encoding/csv` Package Add Extra Quotes to Quoted Strings in CSV Files?

對Go Encoding/CSV 中引用字串的特殊CSV 結果進行故障排除

Go 中的編碼/csv 套件一直是有關處理引用字串的許多爭論的主題在CSV 文件中。本文旨在透過探索使用者在將引號的字串寫入 CSV 檔案時遇到額外引號所觀察到的有趣現象來闡明這個問題。

額外引號之謎

使用者提供的下面的程式碼片段來說明這個問題:

<code class="go">package main

import (
    "encoding/csv"
    "fmt"
    "os"
)

func main() {
    // Create a file to write CSV data
    f, err := os.Create("./test.csv")
    if err != nil {
        log.Fatal("Error: %s", err)
    }
    defer f.Close()

    // Initialize a CSV writer
    w := csv.NewWriter(f)

    // Unquoted string
    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)

    // Quoted string
    record = make([]string, 0)
    record = append(record, "Quoted string")
    s = fmt.Sprintf("%q", s)
    record = append(record, s)
    fmt.Println(record)
    w.Write(record)

    // Flush the writer to save the changes
    w.Flush()
}</code>

執行此程式碼時,帶引號的字串的預期輸出如下:

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

但是,實際獲得的輸出是:

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

引用字串周圍存在額外的引號令人費解,需要進一步調查。

了解 CSV 標準

問題的根源在於CSV(逗號分隔值)檔案格式標準本身。根據標準,欄位中使用的雙引號(") 必須由兩個雙引號("") 表示。這是出於解析目的轉義字元的一種方法。

A (double) quote character in a field must be represented by two (double) quote characters.
  • [逗號分隔值- 維基百科](https://en.wikipedia.org/wiki/Comma-separated_values)

對CSV 寫入的影響

將此規則套用於在程式碼中,使用者確實使用fmt.Sprintf("%q") 正確轉義了引用字串中的引號,但是,encoding/csv 套件透過surrou

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

This 添加了額外的轉義。 🎜>

雖然額外的引號是根據CSV 編碼規範添加的,但可以透過選擇替代編碼格式來避免它們。手動操作字串。特殊行為可以歸因於CSV 標準本身,這需要對雙引號進行轉義以進行解析。

以上是為什麼 Go 的 `encoding/csv` 套件會向 CSV 檔案中的參考字串添加額外的引號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn