Problem reading csv file that has comma and comma and comma

Asked

Viewed 370 times

0

The code reads the file successfully until it hangs on line 6, which has a comma in the middle, I took the comma off line 6, and the err went to line 8 and so on. How do I read the file? ignoring the commas, first time messing with csv file.

Example csv:

Produtos;preco;data
...
camiseta,outros;60;20/10/20019  (a vírgula separando)

O erro:
2019/10/22 20:19:49 record on line 6: wrong number of fields
exit status 1
package main

import (
    "encoding/csv"
    "fmt"
    "log"
    "os"
    "io"
)

func main() {
    csvfile, ferr := os.Open("teste/ncm.csv")
    if ferr != nil {
        log.Fatal(ferr)
    }
    r := csv.NewReader(csvfile)

    for {
        record, err := r.Read()
        if err == io.EOF {
            break
        }
        if err != nil {
            log.Fatal(err)
        }

        fmt.Println(record)
    }
}

1 answer

0


The problem is that in CSV, the comma (,) is the delimiter for each information. In your code apparently you are using the point and comma (;) as a delimiter, but the Ncoder does not know this.

Since the first line has no comma, the Ncoder assumes that each line will have only one information, but when finding a line as a comma it throws an error, because the line would have two information, and therefore its CSV would be inconsistent.

What you need to do is set the semicolon as your delimiter, do it this way:

r := csv.NewReader(csvfile)
r.Comma = ';'

If all lines in your file have the same point number and commas, you will be able to read the file without errors.

  • Value! Now he’s read the whole file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.