此程式碼片段嘗試建立一個包含兩筆記錄的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("Error: %s", err) } defer f.Close() w := csv.NewWriter(f) 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) record = make([]string, 0) record = append(record, "Quoted string") s = fmt.Sprintf("%q", s) record = append(record, 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 的結果標準。根據規範,字段內的雙引號必須用雙引號轉義。因此,CSV 寫入器會自動對引號的字串中的雙引號進行轉義。
CSV 讀取器會在解析過程中自動對雙引號進行轉義,因此無需擔心多餘的引號。引號的字串將被正確地解釋為:
"Cr@zy text with , and \ and \" etc"
這是程式碼的改進版本,刪除了不必要的轉義:
package main
import (
"encoding/csv"
"fmt"
"os"
)
func checkError(e error){
if e != nil {
panic(e)
}
}
func writeCSV(){
fmt.Println("Writing csv")
f, err := os.Create("./test.csv")
checkError(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)
record = []string{
"Quoted string",
s,
}
fmt.Println(record)
w.Write(record)
w.Flush()
}
func readCSV(){
fmt.Println("Reading csv")
file, err := os.Open("./test.csv")
defer file.Close();
cr := csv.NewReader(file)
records, err := cr.ReadAll()
checkError(err)
for _, record := range records {
fmt.Println(record)
}
}
func main() {
writeCSV()
readCSV()
}
Writing csv [Unquoted string Cr@zy text with , and \ and " etc] [Quoted string Cr@zy text with , and \ and " etc] Reading csv [Unquoted string Cr@zy text with , and \ and " etc] [Quoted string Cr@zy text with , and \ and " etc]
以上是為什麼 Go 的 CSV 編寫器會為包含特殊字元的引用字串添加額外的引號?的詳細內容。更多資訊請關注PHP中文網其他相關文章!