Separate Rows in reader

rusi rustompmody at gmail.com
Sun Mar 24 11:57:12 EDT 2013


On Mar 24, 6:49 pm, Tim Chase <python.l... at tim.thechases.com> wrote:
> On 2013-03-24 09:03, Dave Angel wrote:
>
> > >> <SNIP all those quoted lines doubled by anti-social googlegroups>
>
> [THANK YOU!]
>
> > > Sorry my typo in the output here is the correct output that i
> > > need :
>
> > > [('John Konon', 'Ministry of moon Walks', '4567882', '27-Feb'),
> > > ( 'Stacy Kisha', 'Ministry of Man Power', '1234567', 17-Jan')]
>
> > > the difference is that i need a [(row two), (row three), (row
> > > fouth)] . I do not want to display row one which is ['Name', '
> > > Address', 'Telephone', 'Birthday']
>
> > I had to add a delimiter= to accomodate the fact that your data is
> > tab- separated.
>
> Since it has headers, it might make more sense for readability to use
> a DictReader:
>
>   f = file("source.txt", "rb")
>   r = csv.DictReader(f, delimiter='\t')
>   for row in r:
>     print row["Name"], row["Address"], ...
>
> However, if it's just stripping off the first row and operating
> directly on the resulting data, then I'd just be tempted to do
>
>   r = csv.reader(f, delimiter='\t')
>   r.next() # discard the headers, or optionally store them
>   for row in r:
>     ...
>
> -tkc

After doing:

>>> import csv
>>> original = file('friends.csv', 'rU')
>>> reader = csv.reader(original, delimiter='\t')


Stripping of the first line is:
>>> list(reader)[1:]

If for some reason you want to tuplify each row do either:
>>> [tuple(row) for row in list(reader)[1:]]

Or else
>>> map(tuple,list(reader)[1:])

I usually prefer comprehensions to maps. Here though, the map is
shorter. Your choice


Then you can of course make your code more performant thus:
>>> reader.next()
>>> (tuple(row) for row in reader)

In the majority of cases this optimization is not worth it
In any case, strewing prints all over the code is a bad habit (except
for debugging).



More information about the Python-list mailing list