File Open Function with Try & Except Python 2.7.1

94,600

Solution 1

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

Solution 2

This is likely because you want to open the file in read mode. Replace the "U" with "r".

Of course, you can use os.path.isfile('filepath') too.

Solution 3

I think os.path.isfile() is better if you just want to "check" if a file exists since you do not need to actually open the file. Anyway, after open it is a considered best practice to close the file and examples above did not include this.

Share:
94,600
O.rka
Author by

O.rka

I am an academic researcher studying machine-learning and microorganisms

Updated on July 24, 2020

Comments

  • O.rka
    O.rka almost 4 years
    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???

  • kindall
    kindall over 12 years
    To elaborate, the problem identified by OregonTrail is that your return 0 is indented to the same level as your if statement. This puts the return outside the if, so the function returns 0 regardless of whether it got an error or not.
  • O.rka
    O.rka over 12 years
    how do i call the function? do i need to set a file to a variable? if i did that it would just be opening the file . . .
  • OregonTrail
    OregonTrail over 12 years
    I've added some lines to flesh out the example
  • O.rka
    O.rka about 8 years
    I like this better. Is there a version for checking a directory too?
  • mlv
    mlv about 8 years
    isfile is definitely better. For plain files, it should be harmless to open files, but it can have unexpected side-effects if, for example, it's a named pipe. Also, when you leave the scope, the file should close automatically.
  • edesz
    edesz almost 6 years
    This worked well for me. I used f = open(fn, "r"). However, when I used a finally block to close a file that does not exist, I got the error message UnboundLocalError: local variable 'f' referenced before assignment. I could only close the file successfully with an else block and not a finally block - I used else: f.close().
  • OregonTrail
    OregonTrail almost 6 years
    ah, good point, try .. else is the way to go here for resiliant execution