0

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?

2
  • So the loop works the first time through? Commented Jan 14, 2019 at 22:58
  • @SuperStew I don't think it's the loop, but the first time it works it is for the try: except: part Commented Jan 14, 2019 at 22:59

2 Answers 2

3

If a exception happens outside of try: except: it will crash your program. By asking a new input after the except: you are outside the capturing-"context": resulting in your program crashing.

Fix :

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

It is important to also check/handle img being None because imread() can return a None if problems occure with loading the image (file exists / but corrupted... or a .txt)

Sign up to request clarification or add additional context in comments.

Comments

0

This helps!

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.