Python : select a specific line from text

Mehdi ouahabi picture Mehdi ouahabi · Aug 17, 2015 · Viewed 11.1k times · Source

i'm trying to make a code that :

  • open a text file
  • go to the lines that start with "Start"
  • go to line 3 from the lines that start with "start" (previously selected)
  • check if that line contain " contain" word

if yes = print " ok " :

str1 = "Start"

with open("C:...test.txt") as file:
for line in file:
    if str1 in line:
        if "contain" in line:
            print "OK"
        else:
            print "NOK"

i need to integrate the " 3rd line" condition

Answer

alex314159 picture alex314159 · Aug 17, 2015

Might be small overhead, but if your file isn't too big, I'd just dump every line in a list L, then loop through that list - if row r starts with str1, you can just do L[r+3] and check if it contains 'contain'.