encoding/csv: getting a line number of current record when using csv.Reader

866 views
Skip to first unread message

Dan Jackson

unread,
Apr 8, 2021, 12:36:27 PM4/8/21
to golang-nuts
My need is similar to issue #26679 but not the same.

I am using 1.15.8

I have a need for the "current line number" when reading a csv file (with Reader.Read() ) so that I can report errors in the data (not a csv parsing error but errors in the data in the csv file).  In my case, a comment character is being used to allow my user to provide comments in the file for easier maintainability of their csv data.  Because of comments in the file the record number and line number are not the same so any reporting of errors to my user cannot point to any specific line number in the file for the data error ... I have to either give info on the record to my user or tell them the non-commented line number (neither being a user-friendly option as they have to look through the file to see where the real error is instead of going to a specific line number).

Any way to get the true (starting) line number of the current record as a file is being read using the Reader.Read() function?

Thanks
Dan

peterGo

unread,
Apr 8, 2021, 1:50:10 PM4/8/21
to golang-nuts
Dan,

For Go 1.17:

encoding/csv: add the ability to get the line number of a record #44221
https://github.com/golang/go/issues/44221

Peter

nikolay nikolay

unread,
Apr 9, 2021, 1:03:49 AM4/9/21
to golang-nuts
If you CSV is simple, as in does not have multi-line values in columns, \n in line ending — then you can create your own wrapper around io.Reader that counts number of \n before returning to caller []bytes.

-- Nikolay

Tamás Gulácsi

unread,
Apr 9, 2021, 11:57:32 AM4/9/21
to golang-nuts
And if your CSV is not so simple, then extract the number of "\n"-s found in the fields from the line count gathered by counting "\n"-s.

Or re-encode the csv into a "\n" counting io.Writer.
Reply all
Reply to author
Forward
0 new messages