Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Try/Exept prints only ones
#1
Happy Hollowing! If there is such a thing... Smile
I'm scanning files for specific lines, If lines found I append them to lists and count matched lines.
I need to print only the last line from each list and the count number (of matched lines).
I'm using Try/Except to handle empty lists and having a problem with "print". The script I wrote prints only one Print statement, Confused I need to print a lot more than one.

import os
import os.path
import re
from itertools import islice
import io

t0 ='Error 0'
t1 ='Error 1'


logDir = 'C:/Log_Dir/'

with open('C:/somedir/Errors_detailes.txt','w') as fout_w :     ## Append Mode  ##
    fout_w.write("line1"+'\n')

    for fn in os.listdir(logDir):
        if os.path.isfile(os.path.join(logDir, fn)):               
            dir_f = logDir+fn                 
            mylst1 = []
            with io. open(dir_f, encoding='utf-8', errors='ignore') as f : 
                cnttt =0
                cntt1 =0

                lstt0=[]
                lstt1=[]
                
                for line in f : 
                    if t0 in line:
                        cnttt+=1
                        lstt0.append(line)
                        #print (fn+"----->> "+line)
                    
                    elif t1 in line:
                        cntt1+=1
                        lstt1.append(line)
                    #    print (fn+"----->> "+line)                        
                        
                try :
                    print ("-- Count of 'Error - 0' Errors -- "+ str(cnttt)+" --->>>  "+lstt0[-1]+"\n")
                    print ("-- Count of 'Error - 1' Errors -- "+ str(cntt1)+" --->>>  "+lstt1[-1]+"\n")                    
                except Exception as ex:
                    print(ex)
Thank you! Smile
Reply
#2
I'm not sure the try/except is your problem. We don't have your inputs, so it's hard to see what's happening.

If you replace the "try" prints with something that always succeeds like
print(f"dir_f is {dir_f}")
Do you still only get one print?

You could do it as a conditional rather than a try/except.
Reply
#3
Hi, here is an example of input files.


File one :

111111111 Error 0 paaaaa d ffffffff
cv,m dserr
2 333 555555
this is a file 1 Error 0 first file

Second file:
looking for Error 1 in the file
asd 34 nmmmmmmmmmmmm errrrrr
dd m mmmmmmm Error 1 ;;;;;;;;;;;

I'm scanning files for specific lines (with 'Error 0' and "Error 1', If lines found I append them to lists and count matched lines.
I need to print only the last line from each list and the count number (of matched lines).
I'm using Try/Except to handle empty lists and having a problem with "print". The script I wrote prints only one Print statement, Confused I need to print a lot more than one.

If you'll run my snippet, it will print only ones.

I'm trying to print all the last elements from the lists and I cannot.


Thank you!
Reply
#4
It will work if I'll add a second try/except block. I do not understand why it is doing this.

                try :
                    print ("-- Count of 'Error - 0' Errors -- "+ str(cnttt)+" --->>>  "+lstt0[-1]+"\n")                    
                except Exception as ex:
                    print(ex)

                try :
                    print ("-- Count of 'Error - 1' Errors -- "+ str(cntt1)+" --->>>  "+lstt1[-1]+"\n")                    
                except Exception as ex:
                    print(ex)
Reply
#5
Using a simplified version of your example:
cnttt = 1
cntt1 = 0
lstt0 = ['lst0']
lstt1 = []
try :
    print ("-- Count of 'Error - 0' Errors -- "+ str(cnttt)+" --->>>  "+lstt0[-1]+"\n")
    print ("-- Count of 'Error - 1' Errors -- "+ str(cntt1)+" --->>>  "+lstt1[-1]+"\n")                    
except Exception as ex:
    print(ex)
Output:
-- Count of 'Error - 0' Errors -- 1 --->>> lst0 list index out of range
This looks like the exception works. It prints the message followed by the exception. But what happens if we change lst0 = [] and lst1 = ['lst1']. When I do this the output is:
Output:
list index out of range
Why is there only 1 message? The answer is easy if we trace the code. We try to print the first message and it fails because the list is empty and there is nothing to get at lst0[-1]. This throws an exception and we move down to the handler that prints the exception. Execution continues on from that point. It does not jump back to the next line after the exception. Just imagine how horrible that would be if you wrapped an exception handler around a loop. You might never escape.

Wrapping an exception handler around each print statement fixes the problem, because each print statement gets evaluated. However I think this is a case where look before you leap is better than relying on an exception handler.
if (len(lstt0(> 0):
    print ("-- Count of 'Error - 0' Errors -- "+ str(len(lstt0))+" --->>>  "+lstt0[-1]+"\n")
if (len(lstt0) > 0):
    print ("-- Count of 'Error - 1' Errors -- "+ str(len(lstt1))+" --->>>  "+lstt1[-1]+"\n")                    
Reply
#6
To deanhystad,
Thank you for your help but I do not have errors I do not expect, I have a problem printing.

Some of the files I scan do not have "Error 0" or "Error 1" and exception errors are expected.
I have a problem printing the last elements from the lists:
lstt0[-1]
lstt1[-1]
only 1 (one) print statement at a time executes from the Try/Except.
Thank you.
Reply
#7
I am confused. Your second post with two exception handlers made it look like you are wondering why the exception handler does not always print both print statements. Do you understand now why in your original post the second print statement was skipped if the first print statement raised an error?

This last post sounds like you are wondering why you only see one error message from the log file when there may be many. This is because you only print messages once per log file. The print statements are outside the for loop that scans the log file.

Here is a shorter example I used to scan a file of baseball world series teams. I want to count the number of times the Milwaukee anybodies played in the WS and how many times the Chicago White Sox played in the WS.
import os

t0 = 'Milwaukee'
t1 = 'White Sox'
with open(os.path.join(os.getcwd(), 'debug.txt')) as f: 
    t0list=[]
    t1list=[]     
    for line in f :
        if t0 in line:
            t0list.append(line)
         
        elif t1 in line:
            t1list.append(line)
             
    if t0list:
        print(f'{t0} count -- {len(t0list)} --->>>  {t0list[-1]}')
    if t1list:
        print(f'{t1} count -- {len(t1list)} --->>>  {t1list[-1]}')
Output:
Milwaukee count -- 3 --->>> 1982 St. Louis Cardinals (NL) Milwaukee Brewers (AL) 4–3 White Sox count -- 5 --->>> 2005 Chicago White Sox (AL) Houston Astros (NL) 4–0
Even though Milwaukee has been in the WS 3 times, the program only printed the last time against St Louis in 1982. The same thing happened with the White Sox, only printing their last time, a win of Houston in 2005.

If this is the problem you are having, having multiple errors but only seeing one error printed, the problem is where the print statements are. In the example below I print each match as it is identified.
import os

t0 = 'Milwaukee'
t1 = 'White Sox'
with open(os.path.join(os.getcwd(), 'debug.txt')) as f: 
    t0cnt = 0
    t1cnt = 0    
    for line in f :
        if t0 in line:
            t0cnt+=1
            print(f'{t0cnt} {line.strip()}')
         
        elif t1 in line:
            t1cnt+=1
            print(f'{t1cnt} {line.strip()}')
Output:
1 1906 Chicago White Sox (AL) Chicago Cubs (NL) 4–2 2 1917 Chicago White Sox (AL) New York Giants (NL) 4–2 3 1919 Cincinnati Reds (NL) Chicago White Sox (AL) 5–3 1 1957 Milwaukee Braves (NL) New York Yankees (AL) 4–3 2 1958 New York Yankees (AL) Milwaukee Braves (NL) 4–3 4 1959 Los Angeles Dodgers (NL) Chicago White Sox (AL) 4–2 3 1982 St. Louis Cardinals (NL) Milwaukee Brewers (AL) 4–3 5 2005 Chicago White Sox (AL) Houston Astros (NL) 4–0
I could also save the matches in a list as before and then print out all the items in the list.
import os

t0 = 'Milwaukee'
t1 = 'White Sox'
with open(os.path.join(os.getcwd(), 'debug.txt')) as f: 
    t0list=[]  
    t1list=[]   
    for line in f :
        if t0 in line:
            t0list.append(line)
         
        elif t1 in line:
            t1list.append(line)

    print(f'{t0} World Series Appearances = {len(t0list)}')
    for line in t0list:
        print(f'{line.strip()}')

    print(f'\n{t1} World Series Appearances = {len(t1list)}')
    for line in t1list:
        print(f'{line.strip()}')
Output:
Milwaukee World Series Appearances = 3 1957 Milwaukee Braves (NL) New York Yankees (AL) 4–3 1958 New York Yankees (AL) Milwaukee Braves (NL) 4–3 1982 St. Louis Cardinals (NL) Milwaukee Brewers (AL) 4–3 White Sox World Series Appearances = 5 1906 Chicago White Sox (AL) Chicago Cubs (NL) 4–2 1917 Chicago White Sox (AL) New York Giants (NL) 4–2 1919 Cincinnati Reds (NL) Chicago White Sox (AL) 5–3 1959 Los Angeles Dodgers (NL) Chicago White Sox (AL) 4–2 2005 Chicago White Sox (AL) Houston Astros (NL) 4–0
Either way if you want more than one message printed you need the print statement inside a for loop. For error messages in a log file I would print the messages as they occur and then maybe a count at the end of the file.
Reply
#8
To deanhystad,

I tried your suggestion:
                if (len(lstt0(> 0):
                    print ("-- Count of 'Error - 0' Errors -- "+ str(len(lstt0))+" --->>>  "+lstt0[-1]+"\n")
                if (len(lstt1) > 0):
                    print ("-- Count of 'Error - 1' Errors -- "+ str(len(lstt1))+" --->>>  "+lstt1[-1]+"\n"
                                
I added to the script and it produces an error:
    if (len(lstt0(> 0):
                  ^
SyntaxError: invalid syntax

Modified script:
[python]
                for line in f : 
                    if t0 in line:
                        cnttt+=1
                        #print ("COUNT- ",str(cnttt))
                        lstt0.append(line)
                        lofl.append([lstt0])
                        #print (fn+"----->> "+line)
                    
                    elif t1 in line:
                        cntt1+=1
                        lstt1.append(line)
                        lofl.append([lstt1])                        
                        #print (fn+"----->> "+line)  
                if (len(lstt0(> 0):
                    print ("-- Count of 'Error - 0' Errors -- "+ str(len(lstt0))+" --->>>  "+lstt0[-1]+"\n")
                if (len(lstt1) > 0):
                    print ("-- Count of 'Error - 1' Errors -- "+ str(len(lstt1))+" --->>>  "+lstt1[-1]+"\n"
 
[/python]
Reply
#9
In my original post (and the one the flows) I have a problem with the print statement in TRY/EXCEPT block.

I cannot execute multiple prints,
                try :
                    print ("-- Count of 'Error - 0' Errors -- "+ str(cnttt)+" --->>>  "+lstt0[-1]+"\n")
                    print ("-- Count of 'Error - 1' Errors -- "+ str(cntt1)+" --->>>  "+lstt1[-1]+"\n")                    
                except Exception as ex:
                    print(ex)
Only one print executed.

I'd like to print all my prints. I found I can add more TRY/EXCEPT with one print statement.
I just do not want to have 10 it 15 of them in the script.

So. How I can get multiple print statements in one try/except block?

Sorry for the confusion!
And thank you!
Reply
#10
A typo. Should be "if len(lstt0) > 0". I got the second one wrong too, testing lstt0 when it should test lstt1.
if (len(lstt0(> 0):
    print ("-- Count of 'Error - 0' Errors -- "+ str(len(lstt0))+" --->>>  "+lstt0[-1]+"\n")
if (len(lstt0) > 0):
I did a better job on my last post and ran all the examples. This one too.

You don't have to measure the length because Python evaluates an empty list as False when used in an if statement.

"if lstt0" is the same as "if len(lstt0)" is the same as "if len(lstt0) > 0". They all evaluate to False if lstt0 is empty and True if lstt0 is not empty.
tester_V likes this post
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  zfill prints extra et the end of a var tester_V 4 851 Mar-24-2023, 06:59 PM
Last Post: tester_V
  variable prints without being declared. ClockPillow 2 1,771 Jul-11-2021, 12:13 AM
Last Post: ClockPillow
  Output prints Account.id at the end? LastStopDEVS 5 2,718 Dec-19-2020, 05:59 AM
Last Post: buran
  loop only prints last character. mcmxl22 1 1,674 Feb-17-2020, 02:36 AM
Last Post: menator01
  can you understand why this code prints None? arcbal 2 2,700 Mar-13-2019, 02:57 AM
Last Post: arcbal
  What for a file that prints nothing sylas 1 2,143 Sep-12-2018, 01:18 PM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

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