0

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?

1 Answers1

1

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
thebjorn
  • 26,297
  • 11
  • 96
  • 138
  • Thanks for the input. This does work when the first check is successful, but when the exception IOError is raised and it asks for the user to try again, it always errors out with the following: `Traceback (most recent call last): File ".\testing_while_loop.py", line 23, in userFile = input("Enter another filename: ") File "", line 1, in NameError: name 'test_file' is not defined`. I'm not very familiar with using functions, so I'm assuming the error is in there but I haven't found it yet. Do you happen to have any insight? – DarkKnight4251 Apr 03 '19 at 13:28
  • 1
    If you're using Python 2 you'll need to rename `input` to `raw_input`. – thebjorn Apr 03 '19 at 14:04
  • Of course I missed that. Yes, I'm still using Python 2.7 due to some module use. Once I changed `input` to `raw_input` it works perfectly. Thank you. – DarkKnight4251 Apr 03 '19 at 14:06