Reputation: 21
I'm working on a data mining program that is looking for the keyword Background:yellow;
. I want to find it and print the line it appears on and the ten lines that come afterwards. so far I have my program printing the ling that the keyword appears on and the line number, but I can't get it to print the next few lines. My code is below:
I've tried to use print("line{}: {}".format{cnt, line[int:int])
, but it hasn't worked.
import sys
sys.stdout = open('results', 'a')
print(sys.stdout)
filepath = 'test'
with open(filepath) as fp:
line = fp.readline(5)
cnt = 1
while line:
line = fp.readline()
cnt += 1
if str("Background:yellow;") not in line:
continue
elif str("Background:yellow;") in line:
print("""
FOUND
""")
print("line{}: {}".format(cnt, line.strip()))
Upvotes: 1
Views: 1504
Reputation: 143
Complementing the @benjamin answer, if you want to retrieve the grep
output inside of python:
import subprocess
output = subprocess.check_output(
'grep -i -A 10 "Background:yellow;" <filename>',
stderr=subprocess.STDOUT,
shell=True).decode()
lines = output.split('\n')
print(lines)
The first line: lines[0]
, is your matched line.
Upvotes: 0
Reputation: 40773
Here is my approach:
Code:
counter = 0
with open('data.txt') as f:
for line in f:
if 'Background:yellow;' in line:
counter = 11
print() # Optional: Put out an empty line
if counter > 0:
print(line, end='')
counter -= 1
Upvotes: 1
Reputation: 484
An easier solution would be to use grep to do the exact same thing:
grep -i -A 10 "Background:yellow;" <filename>
-A 10 will print the 10 lines after the matching line.
Upvotes: 2