Search code examples
pythonfilefunctiontry-catchexcept

File Open Function with Try & Except Python 2.7.1


def FileCheck(fn):       
       try:
           fn=open("TestFile.txt","U") 
       except IOError: 
           print "Error: File does not appear to exist."
       return 0 

I'm trying to make a function that checks to see if a file exists and if doesn't then it should print the error message and return 0 . Why isn't this working???


Solution

  • You'll need to indent the return 0 if you want to return from within the except block. Also, your argument isn't doing much of anything. Instead of assigning it the filehandle, I assume you want this function to be able to test any file? If not, you don't need any arguments.

    def FileCheck(fn):
        try:
          open(fn, "r")
          return 1
        except IOError:
          print "Error: File does not appear to exist."
          return 0
    
    result = FileCheck("testfile")
    print result