Pankaj Rudrawar
Pankaj Rudrawar

Reputation: 13

using python, Search for a text and print next few lines in python

Currently I am new to Python 3.x coding and looking for some help in text search.

I have large file with more than 8000 lines and need to find a text within this file.Once text found, need subsequent 3 lines along with (text)line redirected to new file.

Any help in this will be greatly appreciated.

Upvotes: 1

Views: 6035

Answers (2)

Trey Hunner
Trey Hunner

Reputation: 11824

One method which opens up output file for appending every time match is found:

search_string = 'search'
with open('infile.txt', mode='r') as infile:
    for line in infile:
        if search_string in line:
            with open('outfile.txt', mode='a') as outfile:
                outfile.writelines([line, next(infile), next(infile)])

Method which opens up output file for writing at the same time as input file is opened and closes out file at the same time input file is closed.

search_string = 'search'
with open('infile.txt', 'r') as infile, open('outfile.txt', 'w') as outfile:
    for line in infile:
        if search_string in line:
            outfile.writelines([line, next(infile), next(infile)])

The next(infile) bits iterate over the next line in the file. This should work for other iterators as well.

Upvotes: 1

J91321
J91321

Reputation: 727

Well when you find that line in file you should be able to do just file.readline() to get next lines. (You should use .find() for string search, this is just quick example).

with open('test.txt', 'r') as infile:
for line in infile:
    if 'myString' in line:
        line2 = infile.readline()
        line3 = infile.readline()
        print(line, end="")
        print(line2, end="")
        print(line3, end="")

Upvotes: 0

Related Questions