Path: csiph.com!x330-a1.tempe.blueboxinc.net!usenet.pasdenom.info!weretis.net!feeder4.news.weretis.net!news.musoftware.de!wum.musoftware.de!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Neil Cerutti Newsgroups: comp.lang.python Subject: Re: How to: Coordinate DictReader and Reader for CSV Date: 21 Nov 2011 15:43:25 GMT Organization: Norwich University Lines: 39 Message-ID: <9iv9stFdboU2@mid.individual.net> 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> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit X-Trace: individual.net hWHddWNCfIZwAcs1J6y5mwqLrAfVUUJ9WIfC5qQWwHv1/Batcn Cancel-Lock: sha1:rmix8niCn8tXadQjBV6Fukc5lqs= User-Agent: slrn/0.9.9p1/mm/ao (Win32) Xref: x330-a1.tempe.blueboxinc.net comp.lang.python:16017 On 2011-11-21, Neil Cerutti wrote: > On 2011-11-21, ray 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