Namedtuples: some unexpected inconveniences

Deborah Swanson python at deborahswanson.net
Fri Apr 14 21:37:13 EDT 2017


Roel Schroeven wrote, on Thursday, April 13, 2017 5:26 PM
> 
> Gregory Ewing schreef op 13/04/2017 9:34:
> > Deborah Swanson wrote:
> >> Peter Otten wrote, on Wednesday, April 12, 2017 1:45 PM
> >>
> >>> Personally I would immediately discard the header row 
> once and for 
> >>> all, not again and again on every operation.
> >> Well, perhaps, but I need the header row to stay in place to write 
> >> the list to a csv when I'm done
> > 
> > That's no problem, just write the header row separately.
> > 
> > Do this at the beginning:
> > 
> >    header = [Record._make(fieldnames)]
> >    records = [Record._make(row) for row in rows]
> > 
> > and then to write out the file:
> > 
> >    writer = csv.writer(outputfile)
> >    writer.writerow(header)
> >    writer.writerows(records)
> 
> I don't even think there's any need to store the field names anywhere 
> else than in fieldnames. So unless I'm missing something, 
> just do this 
> at the beginning:
> 
>      fieldnames = next(rows)
>      Record = namedtuple("Record", fieldnames)
>      records = [Record._make(row) for row in rows]
> 
> and this at the end:
> 
>      writer = csv.writer(outputfile)
>      writer.writerow(fieldnames) # or writer.writerow(Record._fields)
>      writer.writerows(records)
> 
> 
> -- 
> The saddest aspect of life right now is that science gathers 
> knowledge faster than society gathers wisdom.
>    -- Isaac Asimov
> 
> Roel Schroeven

This is essentially what Peter Otten most recently recommended. I know
you got there first, but it is better to only get the header row to name
the fields as you and Greg Ewing suggested, and then use just the
records in processing the field data, using the field names only for the
output.

Thanks,
Deborah




More information about the Python-list mailing list