Obtain the raw line of text read by CSVDictReader when reporting errors?
Oscar Benjamin
oscar.j.benjamin at gmail.com
Wed Sep 21 16:56:33 EDT 2016
On 21 September 2016 at 21:28, Malcolm Greene <python at bdurham.com> wrote:
> Looking for ideas on how I can obtain the raw line of text read by a
> CSVDictReader. I've reviewed the CSV DictReader documentation and there
> are no public attributes that expose this type of data.
>
> My use case is reporting malformed lines detected when my code
> validates the dict of data returned by this object. I would like to log
> the actual line read by the CSVDictReader, not the processed data
> returned in the dict.
You can wrap the file passed into DictReader so that it yelds each
line along with the dict like so:
import csv
def csv_with_line(infile):
last_line = [None]
def line_rememberer():
for line in infile:
last_line[0] = line
yield line
rows = csv.DictReader(line_rememberer())
for lineno, row in enumerate(rows, 2):
yield lineno, last_line[0], row
infile = ['a,b,c', '1,2,3', '4,5,6']
for lineno, line, row in csv_with_line(infile):
print(lineno, line, row)
--
Oscar
More information about the Python-list
mailing list