此代码片段尝试创建一个包含两条记录的 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中文网其他相关文章!