Namedtuples: some unexpected inconveniences
Roel Schroeven
roel at roelschroeven.net
Thu Apr 13 20:25:46 EDT 2017
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
More information about the Python-list
mailing list