Read lines from a file as a shift register with two cells in Python

python

Solution

Sure:

with open("filename", 'r') as file:
    current_line = next(file)  # Get 1st line, advance iterator to 2nd line
    for next_line in file:
        do_something(current_line, next_line)
        current_line = next_line

Problem

I need to read the lines of a file in such way that will behave as a shift register with two cell. For example: ``` with open("filename", 'r') as file: --first iteration-- present = line1 next = line2 do something --second iteration-- present = line2 next = line3 do something --third iteration-- present = line3 next = line 4 do someting and so on.... ``` It can be done with `open(file, 'r')` but it does not guarantee that the file will be closed as the script may stop due to of a "do something" before the last iteration. Any elegant way to do it?

Original source