Lance Collins
Lance Collins

Reputation: 3445

skipping a line while reading a file with a for loop

I am trying to figure out a way to skip the next two lines in a file if a condition in the first line is true. Any ideas on a good way to do this? Here's what I have so far...

def main():
    file = open(r'C:\Users\test\Desktop\test2.txt', 'r+')
    ctr = 1
    for current_line in file:
        assert ctr<3
        if current_line[0:6] == str("001IU"):
            pass
        else:
            if ctr == 1 and current_line[9:11] == str("00"):
                do something...
                ctr += 1
            elif ctr == 1 and current_line[9:11] != str("00"):
                pass #I want it to skip the next two lines in the loop
            elif ctr == 2:
                do something...
                ctr = 1
            else:
                raise ValueError

Upvotes: 6

Views: 26345

Answers (2)

Sven Marnach
Sven Marnach

Reputation: 601709

In Python 2.6 or above, use

next(file)
next(file)

to skip two items of the iterator file, i.e. the next two lines.

Upvotes: 5

yosukesabai
yosukesabai

Reputation: 6244

file.next()
file.next()

i'd do this way...

Upvotes: 1

Related Questions