0

I have a text file with 300 lines. I am looking for a word "ABC" in each line If this word is found i want to print the line before it was found and then the next X lines. This is the code i have so far but i don't know how to print based on given problem statement.


path = ('C:\\Users\\40081\\PycharmProjects\\datalog_parsing')

count2=1
count1=1
num_lines = open('BBCnt123.txt').read().count('\n')
print (num_lines)
count2=count1
while count2<=num_lines:
    file_name = open("BBCnt123.txt", 'r+')
    f= open('BBCnt1234' + '.txt', 'w+')
    for line_no, line in enumerate (file_name):
        line=f.readlines()
        if "BBCnt" in line:
            f.writelines((line[count2-1]) )
        count2= count2+1
file_name.close()
f.close()
anvinder
  • 65
  • 1
  • 10

1 Answers1

0
with open("file.txt","r") as f:
    lines=f.readlines()
    [print(lines[c-1]+lines[c:c+X]) for c,e in enumerate(lines) if "ABC" in e]

Try this list comprehension

whackamadoodle3000
  • 6,185
  • 4
  • 21
  • 38