Search code examples
pythonlisterror-handlingtuplestry-except

Lists, Tuples, and Statistics Program Try-Except Block Error


I am working on a Lists, Tuples, and Statistics Program for my intro class, and am having some difficulty with a try-except block. The program we are supposed to make is supposed to ask for the user to name a file to input, and then give some information about the numbers in that file. I have all of the information displays working correctly, but can't write the try-except block. The program needs to accept only the file name "new_numbers.txt" and nothing else.

Here is the top portion of my code:

    def main():
        #Get the name of the file from the user
        while(True):
                try:
                    input("Enter the name of the file you would like to open: ")
                except ValueError:
                    print("That file does not exist. Please enter a valid file.")
                    break

Solution

  • You need to assign the value from input, and try to open it to see if the file in question is around...:

    def main():
        #Get the name of the file from the user
        while(True):
            try:
                fn = input('Enter the name of the file you would like to open: ')
                f = open(fn)
            except IOError:
                print('File {} does not exist. Please enter a valid file.'.format(fn))
            else:
                break
    

    Also note that you should break only when there is no more error; and in that case the open file object is ready as variable f.