perpetual_wheel
perpetual_wheel

Reputation: 53

Loop over specified rows of a csv file using Python

I am using the package csv in python 2.7

import csv    
f=open('Path\Top.csv')


csv_f = csv.reader(f)
counter = 0
for row in csv_f:
    if counter ==0 :
        next
    # Do some more stuff
    counter += 1

The first row contains headers and i don't wish to include it in the loop. I am trying the above scheme to omit the first row from analysis.

Is there an elegant way of accomplishing the same, the above scheme doesn't work.

Also, how do I iterate from some row i to row j without having to start from first row every time.The file is big and it wastes time to start from 1st row every single time.

Thanks.

Upvotes: 2

Views: 6672

Answers (1)

David Anderson
David Anderson

Reputation: 8616

next is a function, not a control flow statement. Use continue instead to get the behavior you want. You'll also need to increment in the if block since continue will skip the rest of the for loop iteration.

if counter == 0:
    counter += 1
    continue

Alternatively, a cleaner approach (assuming you don't need counter) would be to use next to skip the first row before you get to the for loop. This also demonstrates the correct usage of next. In this example, I'm ignoring the return value of next(csv_f) but it's worth noting that it will contain the CSV header in case you wanted to do something with that before looping over the rows.

csv_f = csv.reader(f)
next(csv_f) # Skip header
for row in csv_f:
    # Do some more stuff
    print row

If you do need counter, a more Pythonic way of doing things would be to use built-in enumerate function.

csv_f = csv.reader(f)
for counter, row in enumerate(csv_f):
    if counter == 0:
        continue
    # Do some more stuff
    print row

Upvotes: 2

Related Questions