登录
首页 >  Golang >  Go问答

go编码/csv中带引号的字符串出现奇怪的CSV结果

来源:stackoverflow

时间:2024-04-14 19:00:34 181浏览 收藏

学习知识要善于思考,思考,再思考!今天golang学习网小编就给大家带来《go编码/csv中带引号的字符串出现奇怪的CSV结果》,以下内容主要包含等知识点,如果你正在学习或准备学习Golang,就都不要错过本文啦~让我们一起来看看吧,能帮助到你就更好了!

问题内容

我有一小段代码让我整个周末都很忙。

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

运行时打印出:

[unquoted string cr@zy text with , and \ and " etc]
[quoted string "cr@zy text with , and \\ and \" etc"]

第二个引用的文本正是我希望在 csv 中看到的内容,但我得到的是:

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

这些额外的引号从何而来以及如何避免它们? 我尝试了很多方法,包括使用 strings.quote 等,但我似乎找不到完美的解决方案。请帮忙?


解决方案


它是将数据存储为 csv 的标准的一部分。 出于解析原因,需要对双引号字符进行转义。

发件人:http://en.wikipedia.org/wiki/Comma-separated_values

您实际上不必担心,因为 csv 读取器不会转义双引号。

示例:

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",
      fmt.sprintf("%q",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"]

这是写入函数的代码。 func (w *Writer) Write(record []string) (err error)

今天关于《go编码/csv中带引号的字符串出现奇怪的CSV结果》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>