Cet extrait de code tente de créer un fichier CSV avec deux enregistrements, l'un avec une chaîne sans guillemets et l'autre avec un guillemet chaîne contenant des caractères spéciaux :
<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>
Cependant, la sortie contient des guillemets supplémentaires entourant la chaîne citée :
Unquoted string,"Cr@zy text with , and \ and "" etc" Quoted string,"""Cr@zy text with , and \ and \"" etc"""
Ce comportement est une conséquence du CSV standard. Selon la spécification, les guillemets doubles dans un champ doivent être protégés par des guillemets doubles. Par conséquent, l'éditeur CSV échappe automatiquement les guillemets doubles dans la chaîne entre guillemets.
Le lecteur CSV supprime automatiquement les guillemets doubles lors de l'analyse, il n'est donc pas nécessaire de s'inquiéter des guillemets supplémentaires . La chaîne citée sera correctement interprétée comme :
"Cr@zy text with , and \ and \" etc"
Voici une version améliorée du code avec les échappements inutiles supprimés :
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]
Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!