Search code examples
pythonpython-2.7linecache

Python : select a specific line from text


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


Solution

  • For better memory usage you can use enumerate for line number tracking:

    str1 = "Start"
    fp = open("C:...test.txt")
    check = 0
    for i,line in enumerate(fp):
        if str1 in line:
            check = i
            continue
        if "contain" in line and (i == check + 3):
            print "OK"
        else:
            print "NOK"
    

    Here i == check + 3 condition will check your 3rd line condition.