'Prompt user to enter a filename until it is valid after FileNotFoundError
I'm stuck on this question where after a FileNotFoundError is caught, the user has to enter filenames until they enter a valid filename or Q to quit. I don't know what the valid filenames are so I cant do if filename != valid_filename so I have to do a loop with FileNotFoundError in it but don't know how. Here's what I got so far
def get_file_object(self):
try:
input_file = open(self.file_name, 'r')
words = input_file.read().split("/n")
except FileNotFoundError:
print("{} cannot be found.").format(self.file_name)
new_file_name = input("Please enter a valid file name or Q to quit:")
Solution 1:[1]
You could add a flag for example.
def get_file_object(self):
flag = True
while flag:
try:
input_file = open(self.file_name, 'r')
words = input_file.read().split("/n")
flag = False
except FileNotFoundError:
print("{} cannot be found.").format(self.file_name)
self.file_name = input("Please enter a valid file name or Q to quit")
if self.file_name == "Q":
print("Quitting...")
flag = False
Solution 2:[2]
See the code below. The approach is to repeat the action till the user is making right choice. The comments will give the idea what we are doing. I know this is repetition.
def get_file_object(self):
is_valid = False
# Assume we don't have a good file at first
while not is_valid:
try:
# Open the file, if its ok then we are done
input_file = open(self.file_name, 'r')
words = input_file.read().split("/n")
is_valid = True # If we get here we are ok, Quit the loop
return words # may be??
except FileNotFoundError:
# If we get here then the file was not found, then we need to do the cycle again!
print("{} cannot be found.").format(self.file_name)
self.file_name = input("Please enter a valid file name or Q to quit")
# If the user wants to quit, then exit the program by making the flag True
is_valid = self.file_name == "Q"
Solution 3:[3]
When FileNotFoundError is caught, you can continue the loop until a valid filename is provided. When this is achieved in the try clause, the program will jump to else clause to break the loop. You can do it like this:
def get_file_object(self):
while True:
try:
if self.file_name == "Q":
print("You have chosen to quit the program.")
break
input_file = open(self.file_name, 'r')
words = input_file.read().split("/n")
except FileNotFoundError:
print("{} cannot be found.").format(self.file_name)
self.file_name = input("Please enter a valid file name or Q to quit")
continue
else:
break
The loop will also break if the user writes Q as the input.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Kris |
| Solution 3 |
