Python Forum
print only last matched line
Thread Rating:
  • 1 Vote(s) - 1 Average
  • 1
  • 2
  • 3
  • 4
  • 5
print only last matched line
#11
You probably don't want two readline's inside the loop
last_lstart = None
last_lstr = None
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!
        last_lstart = cnt
        last_lstr = None
    elif lstr in line:
        last_lstr = cnt
    cnt += 1
    line = fp.readline()
Reply
#12
To deanhystad,
Thanks for the snippet!
I appreciate your help, you the only one trying to help.
I replaced my code with yours and it now prints only one line ( not even ones I'm looking for)
I really do not understand how just one "lstart" will find a pair and it doesn't.
    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!
I replaced my part of the code with yours and it finds a line that not even the one I'm looking for.
what do I do wrong?

f_toread = 'C:\\02\mytext.txt'
lstr  = '-- InitializeRequest'
lstart = "LotComplete"
last_lstart = None
last_lstr = None

with open(f_toread) as fp:  
    line = fp.readline()
    print (line)
    cnt = 1
    flag = False

    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!
                last_lstart = cnt
                last_lstr = None
        elif lstr in line:
            last_lstr = cnt
        cnt += 1
        line = fp.readline()
Reply
#13
The code reads "some lines here" the first line from the file and stops.
Reply
#14
f_toread = 'C:\\02\mytext.txt'
lstr  = '-- InitializeRequest'
lstart = "LotComplete"
last_lstart = None
last_lstr = None
 
with open(f_toread) as fp:  
    line = fp.readline()
    print (line)  # Do not print here.
    cnt = 1
    flag = False
 
    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, last_str)  # Here is where you print your pair
            last_lstart = cnt  # Indent was wrong
            last_lstr = None
        elif lstr in line:
            last_lstr = cnt
        cnt += 1
        line = fp.readline()
Reply
#15
The code does not print anything for some reason (not pair or a match)
Have a question, about the two Vars:
last_lstart = None
last_lstr = None
in here
if last_lstart is not None and last_lstr is None:
what does it mean?
if the Vars not = None then what they are?

I really appreciate your help! are you are a teacher?
Your style reminds me of my school days...
Reply
#16
Interesting. Other than a typo in line 18 (last_lstr, not last_str) it works fine for me. I wrote a little program that generated a file of 1000 sentences with lstr and lstart randomly sprinkled throughout. It found each LotComplete/-- InitializeRequest pair and printed the line numbers to stdout.

None is a special Python object that is often used to create a variable or attribute but not really assign a value. Below I use None to make the variable x and indicate that x doesn't have a real value.
x = None  # Want to make x, but not give it a real value

… some time later...

if x is None:  # If x not assigned a value, assign one now.
    x = 10
The line "if x is None:" is a lot like asking "if x == None:", but instead of comparing values for equivalency, it checks if the object ID of the thing in x is the same the same as None's object ID. I think this may be a holdover form olden times when you could actually change the value of things like True and False in Python. Imagine what would happen if you were allowed to do this:
False = True  # Make False and True have the same value
x = True
if x == True:
    print('x == True')
if x == False:
    print('x == False')
if x is False:
    print('x is False')
Output:
x == True x == False
The last if evaluates to False and the line does not print. Even though x has the same value as False, it is not False. The object ID's don't match.

So back to the question. This test is checking if both last_start and last_lst have been assigned values. If so, that means we saw both of these lines and it is ok to print the pair.
if last_lstart is not None and last_lstr is None:
Reply
#17
Hi,
I do not know what file you are using for this code.
Here is the mytext.txt like file example I posted in the beginning (see below)
When your code is used with it,
it prints one line:
some lines here

LotCompletestring found in line 7
>>>

some lines here
some lines here and more
first line to find --InitializeRequest more stuff
some lines here
some lines here and more
second line to find --LotComplete some stuff here
second line to find --LotComplete some stuff here
some lines here
some lines here and more
first line to find --InitializeRequest more stuff
some lines here
some line here and more
second line to find --LotComplete some stuff here
second line to find --LotComplete some stuff here
second line to find --LotComplete some stuff here
second line to find --LotComplete some stuff here
second line to find --LotComplete some stuff here
second line to find --LotComplete some stuff here
some lines here
some lines here and more
first line to find --InitializeRequest more stuff
some lines here
some line here and more
second lines to find --LotComplete some stuff here
second lines to find --LotComplete some stuff here
second lines to find --LotComplete some stuff here
some lines here
some lines here and more
first line to find --InitializeRequest more stuff
some lines here
some lines here and more
second line to find --LotComplete some stuff here

And the question I asked before.
The two Vars below I declared.
lstr = '-- InitializeRequest'
lstart = 'LotComplete'

if the Vars "last_lstar and last lstr" both not None then what they are?
Where they get values?
The "print(last_lstart, last_str)" not really printing anything.

            if last_lstart is not None and last_lstr is not None:
                # I found a pair!
                print(last_lstart, last_str)  # Here is where you print your pair

thank you for coaching!
I started writing Python scripts about 3 weeks ago Wall and it is not easy for me. Confused
Reply
#18
last_str remembers the cnt where it last saw the last lstr string. In other words it is remembering the line number for where it last saw lstr. last_lstart does the same, but for the last lstart string. If the program is reading a line 3 and it finds lstr, last_lstr will be set to 3. If you would rater print out the paired strings instead of the paired line numbers, you could change the program to save lines in these variables instead of line numbers.

Your program is not finding pairs because you are looking for the wrong strings. Looking at the example file content you supplied, lstr should be '--InitializeRequest', not '-- InitializeRequest'. You have an extra space and this will prevent "lstr in line" from ever being true. And if your program can't find lstr, it will never find a lstart/lstr pair.

Using your file and this program:
f_toread = 'logfile.txt'
lstr  = '--InitializeRequest'
lstart = "--LotComplete"
last_lstart = None
last_lstr = None
  
with open(f_toread) as fp:  
    line = fp.readline()
    print (line)  # Do not print here.
    cnt = 1
    flag = False
  
    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, last_lstr)  # Here is where you print your pair
            last_lstart = cnt  # Indent was wrong
            last_lstr = None
        elif lstr in line:
            last_lstr = cnt
        cnt += 1
        line = fp.readline()
I get this output:
Output:
7 10 18 21 26 29
Scanning through the sample input I think this is correct.
Reply
#19
Well, it is not the place to tell you what I think but you Sir are writing amazing code, at least for me it looks amazing. I tip my hat. If you planning to visit Portland OR, ping me and I'll buy you a beer.
Few more questions, I have never heard or seen anywhere, on the forums for sure, about "it is remembering the line number for where it last saw lstr". How did you find it?
I'll try to modify your code to print lines instead of line numbers but If I'll fail I'll come back for more help.
Thank you very much for the code and the coaching!
Reply
#20
hi deanhystad,
I tried to understand the code for the last few days and how I could print lines not he line numbers but is too complicated for me now.
1. two Vars cnt = 1, flag = False
Why count =1 and why it is declared in the with open block? why not predeclared with the rest of the Vars?
What does the "flag = False" mean and why it is declared in the same block?
2. In the IF block this:
last_lstart = cnt # Indent was wrong
last_lstr = None
Why "last_lstart = cnt" what is that you counting?
Why "last_lstr = None" it is None if it was predeclared None already?
3. in the elif block
last_lstr = cnt Why you count this sctring?
cnt += 1
line = fp.readline() Why you read the line again here if it is was read above in the whit open block?

Thank you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  problem with spliting line in print akbarza 3 529 Jan-23-2024, 04:11 PM
Last Post: deanhystad
  Print the line before the corrent line tester_V 9 1,772 Nov-18-2022, 08:39 AM
Last Post: Gribouillis
  failing to print not matched lines from second file tester_V 14 6,452 Apr-05-2022, 11:56 AM
Last Post: codinglearner
  Print to a New Line when Appending File DaveG 0 1,287 Mar-30-2022, 04:14 AM
Last Post: DaveG
  If match not found print last line tester_V 2 2,980 Apr-26-2021, 05:18 AM
Last Post: tester_V
  print a line break in writelines() method leodavinci1990 1 6,637 Oct-12-2020, 06:36 AM
Last Post: DeaD_EyE
  Print characters in a single line rather than one at a time hhydration 1 2,113 Oct-10-2020, 10:00 PM
Last Post: bowlofred
  How to print string multiple times on new line ace19887 7 6,020 Sep-30-2020, 02:53 PM
Last Post: buran
  Pattern Require Last Line Print() why? Harshil 4 2,548 Aug-08-2020, 04:54 PM
Last Post: Harshil
  Python re.sub text manipulation on matched contents before substituting xilex 2 2,212 May-19-2020, 05:42 AM
Last Post: xilex

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020