Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #16017

Re: How to: Coordinate DictReader and Reader for CSV

From Neil Cerutti <neilc@norwich.edu>
Newsgroups comp.lang.python
Subject Re: How to: Coordinate DictReader and Reader for CSV
Date 2011-11-21 15:43 +0000
Organization Norwich University
Message-ID <9iv9stFdboU2@mid.individual.net> (permalink)
References <2012e1cb-5913-4f39-b102-038a1c95a483@gi1g2000vbb.googlegroups.com> <9iv3q7F1t5U1@mid.individual.net> <04bc73a1-1408-4626-991f-fad94933cb5f@p2g2000vbj.googlegroups.com> <9iv9pbFdboU1@mid.individual.net>

Show all headers | View raw


On 2011-11-21, Neil Cerutti <neilc@norwich.edu> wrote:
> On 2011-11-21, ray <ray@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

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

How to:  Coordinate DictReader and Reader for CSV ray <ray@aarden.us> - 2011-11-21 05:18 -0800
  Re: How to:  Coordinate DictReader and Reader for CSV Neil Cerutti <neilc@norwich.edu> - 2011-11-21 13:59 +0000
    Re: How to: Coordinate DictReader and Reader for CSV ray <ray@aarden.us> - 2011-11-21 07:16 -0800
      Re: How to: Coordinate DictReader and Reader for CSV Neil Cerutti <neilc@norwich.edu> - 2011-11-21 15:41 +0000
        Re: How to: Coordinate DictReader and Reader for CSV Neil Cerutti <neilc@norwich.edu> - 2011-11-21 15:43 +0000
      Re: How to: Coordinate DictReader and Reader for CSV Tim Chase <python.list@tim.thechases.com> - 2011-11-21 12:36 -0600

csiph-web