How to: Coordinate DictReader and Reader for CSV

Neil Cerutti neilc at norwich.edu
Mon Nov 21 10:43:25 EST 2011


On 2011-11-21, Neil Cerutti <neilc at norwich.edu> wrote:
> On 2011-11-21, ray <ray at aarden.us> wrote:
>> Is there a way to capture the keys outside of the for loop so
>> when the for loop is entered, only data is extracted?
>
> I have sometimes done the following type of thing, since
> DictReader doesn't offer an attribute providing the field names.
> This is Python 3.3.2 code, so revise boilerplate if necessary.
>
> # Open once as a csv.reader instance to get the field names, in
> # order.
> with open(in_file_name, newline='') as in_file:
>     reader = csv.reader(in_file)
>     fields = next(reader)

Equal to reader.next() in 2.x Python, I believe.

> # Open it again as a csv.DictReader instance to do actual work,
> # writing revised lines to the output file as I go.
> with open(in_file_name, newline=') as in_file:
>   with open(out_file_name, "w", newline='') as out_file:
>     reader = csv.DictReader(in_file)
>     writer = csv.DictWriter(out_file, fieldnames=fields)
>     # Write header line
>     writer.writerow({f: f for n in fields})

Oops! {f: f for f in fields}. Sorry about that.

>     for record in reader:
>         # Change a few fields
> 	# [...]
> 	writer.writerow(record)


-- 
Neil Cerutti
  "This room is an illusion and is a trap devisut by Satan.  Go
ahead and dauntlessly!  Make rapid progres!"
  --Ghosts 'n Goblins



More information about the Python-list mailing list