Python Forum

Full Version: print only last matched line
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2 3
1. My examples all start with code you provided. Flag and cnt are from your code. They are where they are because that is where you put them. Flag does nothing, I don't know why it was in your code. cnt could be initialized at the top of the program or inside the with. It works fine in either location.

2. cnt was your variable from your code. It counts how many lines were read. I assumed since you were counting lines that you wanted to know the line number of log entries that matched lstart and lstr.

2.a. the readLine locations are again from code that you provided. They work fine, so I did not change them. There are lots of ways you could read all the lines from the log file. For example:
while True:
    line = fp.readline()
    if not line:
        break:  # Break out of loop
    elif lstart in line:
Or using the new walrus operator available in Python 3.8
while line := fp.readline():  # Loop until all lines were read
    if lstart in line:
"2.a. the readLine locations are again from code that you provided. They work fine, so I did not change them. There are lots of ways you could read all the lines from the log file. For example:"
I can read all lines from the file all day ling, it is not the problem reading all lines but printing only ones I want.
For example, I did not declare these two:
"last_lstart"
"last_lstr" 
I tried to print them - no luck.

Thank you>
f_toread = 'logfile.txt'
lstr  = '--InitializeRequest'
lstart = "--LotComplete"
last_lstart = None
last_lstr = None
   
with open(f_toread) as fp:  
    line = fp.readline()
    while line:
        if lstart in line:
            # Did I find a pair?
            if last_lstart is not None and last_lstr is not None:
                # I found a pair!
                print(last_lstart, end = '')
                print(last_lstr)
            last_lstart = line
            last_lstr = None
        elif lstr in line:
            last_lstr = line
        line = fp.readline()
God damn it!
I spent a week and could not make it work but now I see it after you did it.
This part:
last_lstart = line
last_lstr = None
is totaly beyond me for today...very interesting move...awesome.

Thank you again!
last_lstr is set to None to indicate that we have not found a second lines to pair with the most recent first line.

And watch the cursing The appropriate response is a solid head smack.
Pages: 1 2 3