」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 為什麼 Go 的 `encoding/csv` 套件會向 CSV 檔案中的參考字串添加額外的引號?

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

發佈於2024-11-17
瀏覽:598

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

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

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

額外引號之謎

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

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()
}

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

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

然而,實際上得到的輸出是:

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

引用字串周圍存在額外的引號令人費解,需要進一步調查。的雙引號(") 必須由兩個雙引號("") 表示。這是出於分析目的轉義字元的一種方法。

欄位中的(雙)引號字元必須由兩個(雙)引號字元表示。

[Comma-分隔值- 維基百科](https://en.wikipedia.org/wiki/Comma-separated_values)
A (double) quote character in a field must be represented by two (double) quote characters.
    對CSV 寫作的影響
  • 將此規則應用於程式碼、使用者確實透過使用fmt.Sprintf("%q") 正確地轉義了引用字串中的引號。然而,encoding/csv 套件透過 surrou

[Unquoted string Cr@zy text with , and `\` and " etc] 添加了額外的轉義 [帶引號的字串`""""Cr@zy 文本,以及`\` 和\"" 等"""`]

此附加轉義對於遵守CSV 標準是必要的,該標準需要欄位可選擇用雙引號括起來,且欄位中的雙引號必須表示為雙雙引號。透過選擇替代編碼格式來避免。 s = strings.ReplaceAll(s, `"`, `""`)

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

在Go的encoding/csv套件中將引號的字串寫入CSV檔案時觀察到的特殊行為可以歸因於CSV標準本身,它需要透過理解這種底層機制,您可以選擇替代的編碼格式或手動處理字串轉義來實現您想要的結果。

最新教學 更多>

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3