读取前清理 CSV 文件

我正在阅读一个带有encoding/csv库的大 CSV 文件。


但是这个文件有点不标准并且包含非转义引号"打破读者在parser.Read():


2022/06/09 17:33:54 第 2 行第 5 列的解析错误:引用字段中的“无关或缺失”


如果我使用parser.LazyQuotes = true,我会得到:


2022/06/09 17:34:15 记录第2行:字段数错误


错误的 CSV 文件(减少到最小值)foo.csv:


1|2

"a|b

所以我需要删除所有出现的双引号",我目前正在使用从终端对整个文件执行此操作sed 's/"//g',但我想从 Go 脚本中删除它。


知道我正在读取这样的文件,我应该怎么做:


func processCSV(filepath string){

    file, err := os.Open("foo.csv")

    if err != nil {

        log.Fatal(err)

    }


    parser := csv.NewReader(file)

    parser.Comma = '|'

    // parser.LazyQuotes = true


    _, err = parser.Read() // skip headers


    for {

        record, err := parser.Read()

        if err == io.EOF {

            break

        }

        if err != nil {

            log.Fatal(err)

        }


        // process record


    }

}


阿晨1998
浏览 145回答 1
1回答

万千封印

创建一个io.Reader,它从通过底层 io.Reader 读取的数据中删除引号。// rmquote reads r with " removed.type rmquote struct {    r io.Reader}func (c rmquote) Read(p []byte) (int, error) {    n, err := c.r.Read(p)    // i is output position for loop below    i := 0    // for each byte read from the file    for _, b := range p[:n] {        // skip quotes        if b == '"' {            continue        }        // copy byte to output position and advance position        p[i] = b        i++    }    // output position is the new length    return i, err}将其插入 CSV 阅读器和文件之间:parser := csv.NewReader(rmquote{file})
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go