」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 使用「encoding/csv」將引號的字串寫入 CSV 檔案時,為什麼我的 Go 程式碼會產生額外的引號?

使用「encoding/csv」將引號的字串寫入 CSV 檔案時,為什麼我的 Go 程式碼會產生額外的引號?

發佈於2024-11-12
瀏覽:277

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

使用Go 編碼/CSV 引用字串的奇怪CSV 結果

在此程式碼片段中,目標是將資料寫入CSV 文件,確保引用的字串在數據已正確轉義。但是,產生的 CSV 包含額外的引號,導致不一致。

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

帶引號的字串的預期輸出為:

[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 閱讀器會自動對它們進行轉義。因此解決辦法就是在寫帶引號的字串時去掉多餘的雙引號。

修改代號

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

更新輸出

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

透過此更改,帶引號的字串現在已正確轉義,並且刪除了多餘的引號。

最新教學 更多>

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

Copyright© 2022 湘ICP备2022001581号-3