[Csv] Request for enhancement for csv

skip at pobox.com skip at pobox.com
Thu Oct 6 04:25:44 CEST 2005


    paul> When opening a csv file using DictReader, I would like to be able
    paul> to test that the file contains the correct header files as I
    paul> expected.  This would prevent me from opening the incorrect file
    paul> and seeing a indexError.

Paul,

Just specify your fieldnames when you open the file and check the keys and
values of the first row, something like this:

    import csv

    rdr = csv.DictReader(open('somefile.csv', 'rb'),
                         fieldnames=['column1', 'column2', 'column3'],
                         ...)

    headers = rdr.next()
    if headers.keys() != headers.values():
        raise ValueError("Unexpected header line, %s != %s",
                         headers.keys(), headers.values())

-- 
Skip Montanaro
Katrina Benefit Concerts: http://www.musi-cal.com/katrina
skip at pobox.com



More information about the Csv mailing list