1

New programmer here, and well let me start off with the code I have.

try:
    f = input("Please type in the path to your file and press 'Enter'")
    file = open(f,'r')
except FileNotFoundError:
    f = input("File not found please try again.")

What I'm trying to accomplish, is if the user enters a wrong file, to keep asking the user to try again. Maybe I shouldn't be using try/except?

falsetru
  • 336,967
  • 57
  • 673
  • 597
Blakester
  • 99
  • 1
  • 2
  • 9

1 Answers1

2

Embed the statement inside a while loop. break if file is opened successfully.

while True:
    try:
        f = input("Please type in the path to your file and press 'Enter'")
        file = open(f, 'r')
        break
    except FileNotFoundError:
        print('File not found')

NOTE: You may need to handle other exceptions like IOError (even though, there is a file, you may not possible to open it - because of permsssion, wrong file type, ..)

falsetru
  • 336,967
  • 57
  • 673
  • 597
  • Thank you, I will do so! Though it's telling me I need to wait 8 minutes. Also if I wanted to target the IOError, then I would just make another exception for it right. – Blakester Nov 13 '16 at 07:49
  • 1
    Another `except IOError:` if you want to handle `IOException` differently from `FileNotFoundError`. or `except (FileNotFoundError, IOException):` if you want to handle them same way. – falsetru Nov 13 '16 at 07:52