Namedtuples: some unexpected inconveniences
python at deborahswanson.net
Thu Apr 13 21:08:53 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)
> The saddest aspect of life right now is that science gathers
> knowledge faster than society gathers wisdom.
> -- Isaac Asimov
> Roel Schroeven
Thanks Roel. I'll try your version when I get the code reconstructed,
and that might take a few to several days. I'll try to get back to you
though on how it goes.
Read the previous messages if you want the sad story of what happened to
the original code.
More information about the Python-list