13

For my CSV files, every row has the same numbers of columns, except for the last row, which was only one column. So, when I read the file data with "foreach" for getting total number of rows, I get the error that it has the wrong number of fields. How do I fix this error without deleting the last row? The code and CSV file are shown below.

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
1
  • 2
    See go doc encoding/csv.Reader.FieldsPerRecord. Allways, literally allways read the full documentation of any package you use. In the case you read the documentation but could make sense of it: Use -1. Commented Apr 21, 2020 at 6:09

1 Answer 1

37

Disable record length test in the CSV reader by setting FieldsPerRecord to a negative value.

csvr := csv.NewReader(openfile)
csvr.FieldsPerRecord = -1
filedata, err := csvr.ReadAll()

Test the record length in the application code:

for e, value := range filedata {
    if len(value) < 7 {
        continue  // skip short records
    }
    ...
}

Run it on the playground.

Sign up to request clarification or add additional context in comments.

2 Comments

oh okay,thank you, it is work, but how do i store all the data into array ? i must create a slices or array right? but without the length of the filedata, how do i do it ?
@user12952781 Append values to the slices as you go. The example linked from the answer shows how to do this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.