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.