Search code examples
pythonreadline

How do I process the next line when looping through the current lines?


Having a go at converting a vba macro to python. 1st step in python so don't throw stones if so obvious.

Reading a text file 
processing each line
if the line contains a keyword 
    I want to process the next 2 lines 
    (which have the data I need to extract)

How do I select the line i+1 & i+2 if the current (valid) line is i?

Thanks


Solution

  • Here is some code to get you started:

    with open('path/to/file') as f:
        for line in f:
            if 'keyword' in line:
                line = f.readline() # line i+1 
                line = f.readline() # line i+2 
    

    Don't forget to substitute path/to/file and keyword with actual values (and do keep the surrounding '')