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...
In order to iterate over rows, we can use three function iteritems(), iterrows(), itertuples() . These three function will help in iteration over rows.
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']
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With