hpwedoad
hpwedoad

Reputation: 3

I'm trying to find a nice way to read a log file in real time using python

I would like to stop reading when i find a specific string in that file .How can i do it.

os.chdir('/root/.jenkins/jobs/pip2/builds/47')
fo = open('log','w+')

Upvotes: 0

Views: 42

Answers (2)

Martin Evans
Martin Evans

Reputation: 46759

You could use Python's takewhile() function to read all lines up to the point it matches your specific string as follows:

import itertools

specific_string = 'line 5'

with open('input.txt') as f_input:
    for line in itertools.takewhile(lambda x: x.strip() != specific_string, f_input):
        print line,

So if input.txt contained:

line 1
line 2
line 3
line 4
line 5
line 6
line 7            

You would get the following output:

line 1
line 2
line 3
line 4

Or for the opposite effect, to see all lines after your specific string you can use dropwhile() as follows:

import itertools

specific_string = 'line 5'

with open('input.txt') as f_input:
    for line in itertools.dropwhile(lambda x: x.strip() != specific_string, f_input):
        print line,

Giving you:

line 5
line 6
line 7

Upvotes: 0

McGrady
McGrady

Reputation: 11477

You can open the file and use for loop to read it line by line:

with open('file') as f:
    for line in f:
        #read this line
        if 'special string' in line:
            break

The above code only reads one line at a time. When the next line is read, the previous line will be garbage collected.

Upvotes: 1

Related Questions