Before explaining my question I share my code so it it easier to start directly from there.
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'))
I would like the user to input the name of an image file, and whenever the file does not exist in the directory I want the user to input another file name instead of receiving an error message like the following:
FileNotFoundError: [Errno 2] No such file or directory:
In fact, with the code above, after the second mistaken input I receive an error message with exception FileNotFoundError, whereas I would like the loop to go on until an existing file name is given as input. What am I doing wrong in the while loop or in the rest of the code?
try: except:part