File Selection Error Handling


#1

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.")
        try:
            inFile = (fileName, 'a')
            findingFile = 0
        except:
            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 10-3.py", line 98, in <module>
    main()
  File "C:/Users/riley/Documents/Lab 10-3.py", line 29, in main
    readFromFile(averagePints, pints)
  File "C:/Users/riley/Documents/Lab 10-3.py", line 85, in readFromFile
    str1 = inFile.read()
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?


#2

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


#3

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.


#4

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


#5

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.


#6

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


#7

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

inFile = open(fileName, "a")

However, I am still getting the same error.


#8

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