1

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

4
  • 1
    Why do you think that your 'job' will break when it finds two empty files and why do you think that there will be an exception? Commented Mar 30, 2021 at 19:23
  • Well, that's what I'm trying to achieve, but, as I mentioned, it's not doing that. My idea is simple, I "search" for files in a specific directory, if I found 2, I stop my "search" with the exception Commented Mar 30, 2021 at 19:40
  • I know what you are trying to achieve, you manage to state that. What I want to know is why you think that the code you have posted should do that. Commented Mar 30, 2021 at 19:41
  • Well, in my mind I'm doing exactly what I said, I'm looking for the file, I have a if clause whenever I have 2 empty files and the break to break the loop ad return the exception, but, I'm not the expert, I'm just trying to learn and do things. Commented Mar 30, 2021 at 19:48

3 Answers 3

2

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))
Sign up to request clarification or add additional context in comments.

6 Comments

Hmm, ok, but what about the case when there are no empty files?
If there are no empty files, the for loop will run through all the files and empty will be equal to 0. If you want to check, after the for loop, write print(empty)
But it still prints out "I found 2 empty files"
Here I changed the output. It will now print the exact number of empty files up to 2.
But, if I want to specify a folder? this code works, but I need to raise an exception when I find 2 empty files, this is a piece of a major code, so it's a check to continue with the job you could say.
|
1

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)

4 Comments

Thanks Xiddoc, I think I got your point, I will try it out and let you know the result.
No problem! If my answer works, then make sure to click the checkmark on the left of it to mark it as correct.
As you pointed very well, its breaking the for loop and not going to the exception unfortunately...and I'm not managing to change it to raise the exception even inverting and putting the for inside the try
@gfernandes As I said in my answer, if you don't want to go with the method that I wrote (using break, then writing the code outside of the loop) then you can just replace the break command with an error raise, like raise SyntaxError().
0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.