gfernandes
gfernandes

Reputation: 183

Breaking a loop in python

I'm try to check the amount of empty files in a specific folder, the idea is to break my job whenever it finds 2 empty files, my code is as bellow, but. something is missing because it's not showing the Exception.

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)

This is the output message:

Process finished with exit code 0

I have 2 empty files in that folder

Upvotes: 1

Views: 424

Answers (3)

gfernandes
gfernandes

Reputation: 183

Thanks all for the help, I manage to do what I wanted with all your replies, my final piece of code is :

import os
dir_path = 'C:\\temp\\cmm_temp\\tmp\\'
totFilesEmpty = 0
try:
    for fname in os.listdir(dir_path):
        if totFilesEmpty <2:
            full_path = os.path.abspath(os.path.join(dir_path, fname))
            #print("full_path :" + str(full_path))
            file_size = os.stat(full_path).st_size
            # print("file_size :"+ str(file_size))
            file_size_2 = os.path.getsize(full_path)
            #print("fname :" + fname + "file_size_2 : "+ str(file_size_2))
            if file_size_2 == 0:
                totFilesEmpty = totFilesEmpty + 1
        else:
            raise StopIteration
except StopIteration:
    print("number of empty files == 02")

Upvotes: 0

Uros Pocek
Uros Pocek

Reputation: 412

you don't need try-except block for this. Try this code it should work.

import os

empty = 0

# this will loop through every file in your current directory and when it finds 2 files that are empty it will break out of the loop
for file in os.listdir("."):
    # if you want to look only through files with a certain extension add this if file.endswith(".txt"):
    file_size = os.stat(file).st_size
    if file_size <= 0:
        empty += 1
    if empty == 2:
        break

print("I found {} empty files".format(empty))

Upvotes: 2

Xiddoc
Xiddoc

Reputation: 3618

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)

Upvotes: 1

Related Questions