0

I am brand new to the site and python. I'm learning how to deal with errors using try-except. I'm asking for inputs to open a file and search for a line. This is the program i have now. It mostly works...

try:  
    file_str = input("Open what file:")
    input_file = open(file_str) # potential user error
    find_line_str = input("Which line (integer):")
    find_line_int = int(find_line_str) # potential user error
    line_count_int = 1
    for line_str in input_file:
        if line_count_int == find_line_int:
            print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
            break
        line_count_int += 1

    else: # get here if line sought doesn't exist
        print("Line {} of file {} not found".format(find_line_int,file_str))
input_file.close()
except IOError:
    while True:
        file_str = input("That file was not found. Please try again:")
except ValueError:
    find_line_str = input("Invalid line value. Please try again:")

print("End of the program")

Originally, if there was an error it would say "invalid entry, end of program" Now I am trying to make the program keep asking for inputs until the user gets it right.

With the while loop I put in my except IOError it just loops forever even if I enter a valid file name. If I just ask for input it ends the program after entry.

How do I get it to go back and run the for loop after it receives a valid input? Ive been trying to figure this out for hours I really appreciate the help.

4 Answers4

2

In a nutshell

while True:
    try:  
        #code
        break #success case
    except IOError:
        #error display
        #no break, the loop goes on
Diane M
  • 1,503
  • 1
  • 12
  • 23
  • Best answer. The question needs all the detail because the questioner doesn't know what's wrong. The answer is far clearer for having the irrelevant stuff omitted. Also a template for "keep trying, catching exceptions, until we succeed". – nigel222 May 26 '16 at 08:28
1

Updated version of your own script. Added a while loop. The following script will start again from top in case of ValueError or IOError.

while True:
    try:  
        file_str = input("Open what file:")
        input_file = open(file_str) # potential user error
        find_line_str = input("Which line (integer):")
        find_line_int = int(find_line_str) # potential user error
        line_count_int = 1
        for line_str in input_file:
            if line_count_int == find_line_int:
                print("Line {} of file {} is {}".format(find_line_int, file_str,line_str))
                break
            line_count_int += 1

        else: # get here if line sought doesn't exist
            print("Line {} of file {} not found".format(find_line_int,file_str))
        input_file.close()
        break
    except IOError:
        print "That file was not found. Please try again:"
    except ValueError:
        print "Invalid line value. Please try again:"

print("End of the program")
Hassan Mehmood
  • 1,414
  • 1
  • 14
  • 22
1

With the while loop I put in my except IOError it just loops forever even if I enter a valid file name. If I just ask for input it ends the program after entry.

Of course it would:

except IOError:
    while True:
        file_str = input("That file was not found. Please try again:")

Once the first IOError is occurred there is no way to break from that while loop.

As a rule of thumb, you should keep the least amount of lines in each try block. This way you will have a finer control over what line raised the exception.

In this case, you should try opening the file in a while loop, breaking if succeeding and keep looping if an exception occurred:

while True:
    file_str = input("Open what file:")
    try:
        input_file = open(file_str) # potential user error
        break
    except IOError:
        print('File not found. Try again')
# rest of code
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
0

Your try/except(s) should be put in a while-condition loop.

To exit the loop you can then either:

  • set a condition flag as True before entering the loop and as False as soon as entry is ok - you'll keep looping on any error
  • or put a 'break' at the end of a correct entry within a 'while True:' loop

In both case, you should accept also quitting the loop on some request from the user (something as a 'cancel' use-case).

Schmouk
  • 327
  • 2
  • 6