There must be a better way

Neil Cerutti neilc at norwich.edu
Tue Apr 23 09:36:19 EDT 2013


On 2013-04-22, Colin J. Williams <cjw at ncf.ca> wrote:
> Since I'm only interested in one or two columns, the simpler
> approach is probably better.

Here's a sketch of how one of my projects handles that situation.
I think the index variables are invaluable documentation, and
make it a bit more robust. (Python 3, so not every bit is
relevant to you).

with open("today.csv", encoding='UTF-8', newline='') as today_file:
    reader = csv.reader(today_file)
    header = next(reader)
    majr_index = header.index('MAJR')
    div_index = header.index('DIV')
    for rec in reader:
        major = rec[majr_index]
        rec[div_index] = DIVISION_TABLE[major]

But a csv.DictReader might still be more efficient. I never
tested. This is the only place I've used this "optimization".
It's fast enough. ;)

-- 
Neil Cerutti



More information about the Python-list mailing list