Python3:如何计算异常数量并打印

我是新手,

我正在尝试做某事,例如,我想打开多个文件并计算其中的单词, 但我想知道无法打开多少个文件。

它是我尝试的:

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)

所以,我得到这个错误:

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

tried something else also, but i think i dont 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 cant print it at the end, because it will be destroyed after execution.

评论