rignpm04
rignpm04

Reputation: 21

How to print multiple lines with line.strip()

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

Answers (3)

Ronald Rodrigues
Ronald Rodrigues

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

Hai Vu
Hai Vu

Reputation: 40773

Here is my approach:

  1. Read the file, line by line
  2. If we find what we are looking for on that line, set a counter to 11 (that means this line, plus 10 more to follow)
  3. Then, if the counter is greater than 0, print that line and decrease the counter

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

SurpriseDog
SurpriseDog

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

Related Questions