On 2016-09-21 21:28, Malcolm Greene 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 could put something between the file and the reader, like this:

import csv

class MyFile:
    def __init__(self, file):
        self.file = file

    def __iter__(self):
        return self

    def __next__(self):
        self.line = next(self.file)

        return self.line

path = '<path to csv>'

with open(path) as file:
    my_file = MyFile(file)
    reader = csv.DictReader(my_file)

    for row in reader:
        print(repr(my_file.line), '=>', row)

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to