Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python csv reader, loop from the second row

Tags:

python

In python 2.7.3, how can I start the loop from the second row? e.g.

first_row = cvsreader.next();
for row in ???: #expect to begin the loop from second row
    blah...blah...
like image 368
GuLearn Avatar asked May 03 '13 02:05

GuLearn


People also ask

How do I iterate over a row in a CSV file?

In order to iterate over rows, we can use three function iteritems(), iterrows(), itertuples() . These three function will help in iteration over rows.


2 Answers

first_row = next(csvreader)  # Compatible with Python 3.x (also 2.7)
for row in csvreader:  # begins with second row
    # ...

Testing it really works:

>>> import csv
>>> csvreader = csv.reader(['first,second', '2,a', '3,b'])
>>> header = next(csvreader)
>>> for line in csvreader:
    print line
['2', 'a']
['3', 'b']
like image 85
Wesley Baugh Avatar answered Nov 15 '22 18:11

Wesley Baugh


next(reader, None) # Don't raise exception if no line exists

looks most readable IMO

The other alternative is

from itertools import islice
for row in islice(reader, 1, None)

However shouldn't you be using the header? Consider a csv.DictReader which by default sets the fieldnames to the first line.

like image 43
jamylak Avatar answered Nov 15 '22 18:11

jamylak