DarkKnight4251
DarkKnight4251

Reputation: 53

How to fix error exception to allow for retries without the exception looping in Python

I'm attempting to write error handling in Python 2.7 for when an IOError exception is raised after a user enters a filename.

I have tried a couple of solutions our there on the internet including:

How to retry after exception? Get a Try statement to loop around until correct value obtained

This is my original code:

while True: 
    try:
        with open (userFile, 'r') as txtFile:
            for curLine in txtFile:
                curLine = curLine.rstrip("\n\r")
                idList.append(curLine)
    except IOError:
        print("File does not exist")

Whenever the IOError exception is raised it goes into an infinite loop, printing "File does not exist" over and over again. In the instance where I limit the attempts by adding a range, it goes through that range, printing over and over again and then exits the script. Does anyone have an idea why this keeps looping when the exception is raised?

Upvotes: 0

Views: 345

Answers (1)

thebjorn
thebjorn

Reputation: 27351

This will be much easier if you split the separate concerns into functions, i.e. (i) warning the user if a file doesn't exist and (ii) reading the contents of the file into a list of lines:

def read_file(f):
    # you can't read a file line-by-line and get line endings that match '\n\r'
    # the following will match what your code is trying to do, but perhaps not 
    # what you want to accomplish..?
    return f.read().split("\n\r")  # are you sure you haven't switched these..?

def checked_read_file(fname):
    try:
        with open(fname, 'rb') as fp:  # you'll probably need binary mode to read \r
            return read_file(fp)
    except IOError:
        print("File does not exist")
        return False

then you can write your while loop:

while True:
    result = checked_read_file(user_file)
    if result is not False:  # this is correct since the empty list is false-y
        break
    user_file = input("Enter another filename: ")  # or user_file = raw_input("...: ") if you're on Python 2

# here result is an array of lines from the file

Upvotes: 1

Related Questions