Search code examples
pythonpython-3.xtry-except

How to count number of occurred exceptions and print it?


I'm trying to do something. I want to open multiple files and count the words in it for example, but I want to know how many of files couldn't be open.

Its what I tried:

i = 0
def word_count(file_name):
    try:
        with open(file_name) as f:
            content = f.read()
    except FileNotFoundError:
        pass
        i = 0
        i += 1
    else:
        words = content.split()
        word_count = len(words)
        print(f'file {file_name} has {word_count} words.')


file_name = ['data1.txt','a.txt','data2w.txt','b.txt','data3w.txt','data4w.txt']
for names in file_name:
    word_count(names)
print(len(file_name) - i , 'files weren\'t found')
print (i)

So, I get this error:

runfile('D:/~/my')
file data1.txt has 13 words.
file data2w.txt has 24 words.
file data3w.txt has 21 words.
file data4w.txt has 108 words.
Traceback (most recent call last):

  File "D:\~\my\readtrydeffunc.py", line 27, in <module>
    print(len(file_name) - i , 'files weren\'t found')

NameError: name 'i' is not defined

I tried something else also, but I think I don't understand the meaning of scopes well. I think its because i is assigned out of except scope, but when I assign i = 0 in except scope, I can't print it at the end, because it will be destroyed after execution.


Solution

  • Yes, you're on the right track. You need to define and increment i outside the function, or pass the value through the function, increment, and return the new value. Defining i outside the function is more common, and more Pythonic.

    def count_words(file_name):
        with open(file_name) as f:
            content = f.read()
        words = content.split()
        word_count = len(words)
        #print(f'file {file_name} has {word_count} words.')
        return word_count
    
    
    file_name = ['data1.txt','a.txt','data2w.txt','b.txt','data3w.txt','data4w.txt']
    
    i = 0
    for names in file_name:
        try:
            result = count_words(names)
        except FileNotFoundError:
            i += 1
    
    print(i, 'files weren\'t found')