如何修复golang中CSV文件中缺少逗号的“错误数量的字段”?

对于我的 CSV 文件,每一行都有相同的列数,但对于最后一行,那只有一列,所以当我用“foreach”读取文件数据以获得总行数时,我遇到了错误字段数,如何在不删除最后一行的情况下修复此错误?此处的代码和 CSV 文件:


openfile, err := os.Open(filepath)

    checkError("Error in reading the file\n", err)


    fmt.Println("Already open filepath :", filepath)


    //read the data of file

    filedata, err := csv.NewReader(openfile).ReadAll()

    checkError("Error in reading the file\n", err)


    leg := len(filedata)


    fmt.Println("total no of rows:", leg)


    close := make([]string, leg)

    date := make([]string, leg)

    open := make([]string, leg)

    high := make([]string, leg)

    low := make([]string, leg)

    adjustclose := make([]string, leg)

    volume := make([]string, leg)


    for e, value := range filedata {

        date[e] = value[0]

        open[e] = value[1]

        high[e] = value[2]

        low[e] = value[3]

        close[e] = value[4]

        adjustclose[e] = value[5]

        volume[e] = value[6]


    }

2020-03-24,21,21,21,21,21,5


2020-04-06,20.8,20.8,20.8,20.8,20.8,19


2020-04-07,20.4,20.4,20.4,20.4,20.4,5


2020-04-09,20.4,20.4,20.4,20.4,20.4,10


292


一只斗牛犬
浏览 148回答 1
1回答

喵喵时光机

通过将FieldsPerRecord设置为负值来禁用 CSV 阅读器中的记录长度测试。csvr := csv.NewReader(openfile)csvr.FieldsPerRecord = -1filedata, err := csvr.ReadAll()测试应用代码中的记录长度:for e, value := range filedata {&nbsp; &nbsp; if len(value) < 7 {&nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; // skip short records&nbsp; &nbsp; }&nbsp; &nbsp; ...}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go