1

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

Mehdi ouahabi
  • 67
  • 1
  • 2
  • 11

4 Answers4

1

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.

Deep Shah
  • 257
  • 2
  • 9
0

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

alex314159
  • 3,159
  • 2
  • 20
  • 28
0

Use two list to store the positions match your rule.

Then check out the position match your relative offset.

start_lines = []
contains_lines = []
with open("C:...test.txt") as inp:
    line_num = 0
    for line in inp:
        if line.startswith("start"):
            start_lines.append(line_num)

        if "contains" in line:
            contains_lines.append(line_num)

        line_num += 1

print [line_num for line_num in contains_lines if line_num - 3 in start_line]
luoluo
  • 5,353
  • 3
  • 30
  • 41
0

@Mehdi ouahabi you motioned that "go to the line that start with Start", so we check only the lines those start with "Start", and not those contain Start in the middle or at the end :

with open("test.txt") as file:
    for line in file:
        if line.startswith("Start"): #instead of "str1 in line" 
            if "contain" in line: print "OK"
            else: print "NOK"

***EDIT:***in this case you will check if a line start/ contain today's date

from datetime import date
with open("test.txt") as file:
    for line in file:
       #if str(date.today()) in line:#check if today's date exist in the line
       if line.startswith(str(date.today())): #check if the line start with today's dates
            if "contain" in line: print "OK"
            else: print "NOK"