尝试在while循环中执行其他操作-python
在解释我的问题之前,我会分享我的代码,这样就更容易直接从那里开始尝试在while循环中执行其他操作-python,python,while-loop,try-except,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')) e
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
,而我希望循环继续进行,直到给出一个现有文件名作为输入。当循环或代码的其余部分时,我在中做错了什么?如果异常发生在之外,请尝试:除了:
它将使程序崩溃。通过在之后请求一个新的输入,除了:
之外,您在捕获“上下文”之外:导致您的程序崩溃
修正:
检查/处理img是否为None
也很重要,因为imread()
可以返回None
如果加载图像时出现问题(文件存在/但已损坏…或.txt)如果异常发生在之外,请尝试:除非:
它会使程序崩溃。通过在之后请求一个新的输入,除了:
之外,您在捕获“上下文”之外:导致您的程序崩溃
修正:
检查/处理img是否为None
也很重要,因为imread()
可以返回None
,如果加载图像时出现问题(文件存在/但已损坏…或.txt)这很有帮助强>
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
这很有帮助强>
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
所以循环第一次通过?@supersew我不认为它是循环,但是它第一次工作是为了尝试:除了:
部分所以循环第一次通过?@supersew我不认为它是循环,但是它第一次工作是为了尝试:除了:
部分