justik
justik

Reputation: 4255

Python, line iterator

I am processing a file line by line

for line in mix_files[i]:
    if my_string in line:
       use the next line # How to get the next line

After a line containing the text is found, I need to work with the next line. Is there any easy way how to get the next line (e.g., increment an iterator), instead of the less confortable method:

get line number -> increment line number -> use the next line

Thanks for your help.

Upvotes: 2

Views: 3742

Answers (2)

James
James

Reputation: 2795

Martijn's response is good, but you could also use enumerate:

for j, line in enumerate(mix_files[i]):
    if my_string in line:
        try:
            next_line = mix_files[i][j+1]
        except IndexError:
            handle_end_of_file()
        else:
            do_whatever_with_next_line()

Upvotes: -1

Martijn Pieters
Martijn Pieters

Reputation: 1122162

Yes, use the next() function on the iterator:

next_line = next(mix_files[i])

Note that this can raise StopIteration if the file has no more lines. You can tell next() to return a default value instead:

next_line = next(mix_files[i], None)

which will be returned instead of raising the exception.

Upvotes: 3

Related Questions