0

I'm working on a program that accepts a file name as an input, I'm trying to add an error check so that when an invalid file is entered it doesn't break the program, but I'm not quite sure how to do it.

Currently I'm just using

image1 = Image.open(raw_input('Enter your first image name: '))

Essentially what I need is some type of loop in the event that a file isn't there. For example the file I'm using is june_subset_gray.tif, but if someone wrote jne_subset_gray.tif rather than prompting them to try again it would just break. Also I don't want to hard code what it could be because something could name their file picture.jpeg, or alaska.tif.

With that said I'm guessing I'm looking for something that will loop in the event that the file being called doesn't exist.

Thanks for all the responses in advance. This wasn't covered in my programming class at all so I'm at the mercy of google and stackoverflow.

  • Read about try/except https://docs.python.org/2.7/tutorial/errors.html – David Bern Dec 12 '16 at 21:36
  • You will have to get out of asking for the filename in the Image.open line. Instead, you need to get the input value, test for file exists, and only then try the Image.open using the variable as the filename. – Laughing Vergil Dec 12 '16 at 21:38
  • [os.path.exists](https://docs.python.org/3/library/os.path.html#os.path.exists), [os.path.isfile](https://docs.python.org/3/library/os.path.html#os.path.isfile) but it doesn't check if file is correct image and still you may need `try/except` with `open()` – furas Dec 12 '16 at 21:39
  • @LaughingVergil - depending on what `Image` is, it likely raises an error on failure so there is no need to test externally. – tdelaney Dec 12 '16 at 21:40

1 Answers1

3

A quick while loop will do it

while True:
    try:
        image1 = Image.open(raw_input('Enter your first image name: '))
        break
    except IOError:
        print("invalid filename, try again")

I'm not sure what Image is, but it may raise several different types of errors. For instance, what if the user inputs a valid file name but its not an image file. Read its help and experiment to see if there are other exceptions to catch.

tdelaney
  • 73,364
  • 6
  • 83
  • 116