首頁  >  文章  >  後端開發  >  在寫入和讀取 CSV 檔案時,Go 的 `encoding/csv` 套件如何處理雙引號轉義?

在寫入和讀取 CSV 檔案時,Go 的 `encoding/csv` 套件如何處理雙引號轉義?

Barbara Streisand
Barbara Streisand原創
2024-10-25 10:07:48746瀏覽

How does Go's `encoding/csv` package handle double quote escaping when writing and reading CSV files?

Go 的編碼/csv 中的CSV 雙引號轉義

當使用Encoding/csv 套件在Go 中處理CSV 檔案時,至關重要的是了解如何處理雙引號字元("")。雙引號用於括起包含逗號等特殊字元的字串,否則可能會破壞 CSV 格式。

在 Go 中,寫入 CSV 檔案時,轉義字串中的雙引號字元非常重要。 coding/csv 套件會自動執行此操作,在字串中的任何雙引號周圍添加額外的雙引號。這是 CSV 標準的一部分,需要轉義雙引號以確保解析準確性。

範例:

<code class="go">import (
    "encoding/csv"
    "fmt"
    "os"
)

func main() {
    f, err := os.Create("./test.csv")
    if err != nil {
        log.Fatal("Error: %s", 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)

    // Quote the string to escape double quotes
    record = []string{
        "Quoted string",
        fmt.Sprintf("%q", s),
    }
    fmt.Println(record)
    w.Write(record)

    w.Flush()
}</code>

當腳本運作時,輸出會顯示用雙引號括起來的字串:

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

但是,從CSV 檔案讀取時,encoding/csv 套件會自動取消轉義任何轉義的雙引號。這意味著字串將被正確解析,沒有任何額外的雙引號。

讀取函數範例:

<code class="go">func readCSV() {
    file, err := os.Open("./test.csv")
    defer file.Close()
    cr := csv.NewReader(file)
    records, err := cr.ReadAll()
    if err != nil {
        log.Fatal("Error: %s", err)
    }
    for _, record := range records {
        fmt.Println(record)
    }
}</code>

當呼叫讀取函數時,您將查看輸出:

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

這顯示了在寫入和讀取操作期間如何處理雙引號,確保正確儲存和檢索資料。

以上是在寫入和讀取 CSV 檔案時,Go 的 `encoding/csv` 套件如何處理雙引號轉義?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

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