2

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.

1 Answer 1

2

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
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the information about continue and next. Is there any way to iterate over custom row numbers, say from row i to row j besides starting from first row every single time?
@perpetual_wheel Take a look at itertools.islice (docs.python.org/2/library/itertools.html#itertools.islice). This will let you iterate over a specified start and stop interval.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.