Python3:如何计算发生的异常数并打印出来

问题描述 投票:0回答:3

我是新手,

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

我尝试过的内容:

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

也尝试了其他方法,但是我认为我不太了解合并范围的含义,我认为是因为我被分配了除合并范围之外的其他内容,但是当我在i = 0范围中分配了except时,我无法在结束,因为它将在执行后销毁。

python python-3.x try-except
3个回答
1
投票

是的,您在正确的轨道上。您需要在函数外部定义和递增i,或通过函数传递值,递增并返回新值。在函数之外定义i更为常见,并且更加Python化。

def word_count(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 = word_count(names)
    except FileNotFoundError:
        i += 1

print(i, 'files weren\'t found')

0
投票

我建议将其分为2个功能;一个用于处理单词计数,第二个用于控制脚本的流程。控件应该处理任何出现的错误以及处理和从这些错误中得到的反馈。

def word_count(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.')

def file_parser(files):
    i = 0
    for file in files:
        try:
            word_count(file)
        except FileNotFoundError:
            i+=1
    if i > 0:
        print(f'{i} files were not found')

file_names = ['data1.txt','a.txt','data2w.txt','b.txt','data3w.txt','data4w.txt']
file_parser(file_names)

0
投票

虽然应该将代码重构为不使用global variables,但使代码运行的最小修改是删除pass子句中的i = 0except,并要求i为在您的函数内部全局使用:

def word_count(file_name):
    global i  # use a `i` variable defined globally
    try:
        with open(file_name) as f:
            content = f.read()
    except FileNotFoundError:
        i += 1  # increment `i` when the file is not found
    else:
        words = content.split()
        word_count = len(words)
        print(f'file {file_name} has {word_count} words.')


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

请注意,i将包含未找到的文件数。

© www.soinside.com 2019 - 2024. All rights reserved.