尝试在while循环中除外-python

时间:2019-01-14 22:55:06

标签: python while-loop try-except

在解释我的问题之前,我分享了我的代码,因此可以更轻松地直接从那里开始。

import matplotlib.pylab as plt
import os

while True:
    try:
        img_name = input('Enter the image file name: ')
        img = plt.imread(os.path.join(work_dir, 'new_images_from_web\\', img_name + '.jpg'))
    except FileNotFoundError:
        print('Entered image name does not exist.')
        img_name = input('Please enter another image file name: ')
        img = plt.imread(os.path.join(work_dir, 'new_images_from_web\\', img_name + '.jpg'))

我希望用户输入图像文件的名称,只要目录中不存在该文件,我都希望用户输入另一个文件名,而不是收到如下错误消息:

FileNotFoundError: [Errno 2] No such file or directory:

实际上,使用上面的代码,在第二次输入错误后,我收到一条错误消息,异常为FileNotFoundError,而我希望循环继续进行,直到给出现有的文件名作为输入为止。在while循环或其余代码中,我在做什么错了?

2 个答案:

答案 0 :(得分:3)

如果exception发生在try: except:之外,则会使您的程序崩溃。在except:之后询问新的输入,您就不在捕获“上下文”之列:导致程序崩溃。

修复:

import matplotlib.pylab as plt
import os

while True:
    try:
        img_name = input('Enter the image file name: ')
        img = plt.imread(os.path.join(work_dir, 'new_images_from_web\\', img_name + '.jpg'))
        if img is None:
            print("Problem loading image")
        else:
            break  
    except FileNotFoundError:
        print('Entered image name does not exist.')

# or check img here if you allow a None image to "break" from above
if img:
    # do smth with img if not None

同样重要的是还要检查/处理img是否为None,因为如果在加载图像时出现问题(文件存在/但已损坏...或...,imread()可以返回None .txt)

答案 1 :(得分:0)

这有帮助!

while Ture:
    try:
        img_name = input('Enter the image file name: ')
        img = plt.imread(os.path.join(work_dir, 'new_images_from_web\\', img_name + '.jpg'))
        if not img:
            print("Err")
        else:
            break
    except FileNotFoundError:
        print('Entered image name does not exist.')
    else:
        break