The break keyword exits the current loop. In your case, this is the loop that Python enters:
for fname in os.listdir(dir_path):
<code>
<next>
If you have the break keyword anywhere in here (except if it's in a nested loop), then it will exit the place where <code> is written and will continue to execute whatever is written at the <next> segment. Therefore, in your code segment, the break keyword ends the for loop (therefore ignoring all the try/except keywords you've placed) and goes on to after the for loop (where it is the end of the code, and therefore the program terminates).
for fname in os.listdir(dir_path):
try:
if file_size < 2:
totFilesEmpty = totFilesEmpty + 1
else:
# Here is that break keyword that we're talking about
break
except Exception as ab:
# This will only happen if there is an error in the code
print("number of empty files == 02", ab)
# The break keyword now jumps to here!
This is not the most Pythonic way to do things, but a way to merge the breaking of the for loop with your code would be to raise an error instead, which would then be caught by the except keyword. You could do this by replacing your break command with an error raise, like raise SyntaxError(). A better way, however, would be to print the text you want at the end of the code, outside of the loop. An implementation of this would be like so:
import os
dir_path = 'C:\\temp\\cmm_temp\\tmp\\'
totFilesEmpty = 0
for fname in os.listdir(dir_path):
try:
full_path = os.path.abspath(os.path.join(dir_path, fname))
file_size = os.stat(full_path).st_size
if file_size < 2:
totFilesEmpty = totFilesEmpty + 1
else:
break
except Exception as ab:
print("number of empty files == 02", ab)
# Break command skips to here
print("number of empty files == 02", ab)