0

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

JXB
  • 29
  • 5

2 Answers2

0

This is one way to do that in python:

with open ('text.txt') as text_file :
    for line in text_file :
        if 'keyword' in line :
            first_line = text_file.readline ()
            second_line = text_file.readline ()

print (first_line, second_line)
bashBedlam
  • 1,402
  • 1
  • 7
  • 11
0

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 '')

Emrah Diril
  • 1,687
  • 1
  • 19
  • 27
  • Thanks. make sense now. Already "expanded" by adding:- TheInputFile.readline().strip() for the 2 lines and I need and joining them for data extraction – JXB Mar 08 '20 at 13:51