File Selection Error Handling


I am creating an application that takes the input of pints of blood donated each week. It writes the information into a text file as well as retrieves the information. I want to put in some sort of error handling for when the user inputs an invalid file name. This is what I have tried:

 findingFile = 1
    while (findingFile == 1):
        fileName = input("Select a file to read.")
            inFile = (fileName, 'a')
            findingFile = 0
            print ('File not found, please select a valid file.')

I test this code and this is the error that I get:

Select a file to read.adfadfadf
Traceback (most recent call last):
  File "C:/Users/riley/Documents/Lab", line 98, in <module>
  File "C:/Users/riley/Documents/Lab", line 29, in main
    readFromFile(averagePints, pints)
  File "C:/Users/riley/Documents/Lab", line 85, in readFromFile
    str1 =
AttributeError: 'tuple' object has no attribute 'read'

Process finished with exit code 1

Could someone give me an idea of how to deal with this error handling?


There is the tuple to which the error message is referring. Is that line written correctly?


Yes. What I am trying to do is to have the user type the name of the desired file, store the name as a string, and then have the application check to see if the file exists. If it doesn’t, then have the application return saying that the file does not exist and then have the user enter another file name.


But the file name cannot be a tuple, it should reference an i/o object.


I am not actually trying to create a tuple. I am just trying to tell the application that I want to modify the file that the user selects.


That is a tuple. Should it be an open expression?


Alright, so I changed it. This is what it looks like now:

inFile = open(fileName, "a")

However, I am still getting the same error.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.