[Tutor] Resuming one block of code continuously after exception in try/except construction

Steven D'Aprano steve at pearwood.info
Mon Jul 7 05:19:11 CEST 2014


On Sun, Jul 06, 2014 at 11:00:38PM +0200, Ali Mammadov wrote:
> Hello fellow coders!
> Today I encountered a small difficulty while working with files.As a common
> pratice, I want my function to check user's input(in this case it's file
> name) and re-ask it again and again(until correct) offering him two
> choices: re-enter file name or close program.I've decided to use try/except
> construction in this particular task. After a bit of googling, I still
> didn't figure out how and if it's possible to re-run code in try part again
> if exception raises.

That's kind of tricky, because you have two different exceptional 
circumstances, and you want to do something different in each case. 
The best way, I think, is two separate the two parts into two 
functions:


import sys

def get_filename(extra_prompt):
    if extra_prompt:
        print(extra_prompt)
    print("Enter a file name, or type Ctrl-D to exit the program.")
    # On Windows, I think you need Ctrl-Z [enter] instead of Ctrl-D.
    try:
        return input("File name: ")  # Use raw_input in Python 2.
    except EOFError:
        sys.exit()


def get_file():
    f = None
    prompt = ""
    while f is None:
        name = get_filename(prompt)
        try:
            f = open(name, "r")
        # Python 3 exceptions. For Python 2, see below.
        except FileNotFoundError:
            prompt = "File not found; please try again."
        except IsADirectoryError:
            prompt = "That is a directory; please try again."
        except PermissionError:
            prompt = ("You do not have permission to open that"
                      + " file. Please try again.")
        # This must come last.
        except IOError as err:
            prompt = "%s : please try again." % err
    return f


with get_file() as f:
    for line in f:
         print(line)




In Python 2, we don't have all the different sorts of exceptions. 
Instead, you have to catch IOError only, and then inspect the errno 
attribute of the exception to find out what it is:

        try:
            f = open(name, "r")
        except IOError as err:
            if err.errno == 2:
                prompt = "File not found; please try again."
            elif err.errno == 21:
                prompt = "That is a directory; please try again."
            elif err.errno == 13:
                prompt = ("You do not have permission to open that"
                          + " file. Please try again.")


Unfortunately, the error codes can be different on different operating 
systems. To write platform-independent code, you should import the errno 
module and check the error code by name:

           if err.errno == errno.ENOENT:

etc.



-- 
Steven


More information about the Tutor mailing list