9
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
  • 178,883
  • 35
  • 278
  • 309
O.rka
  • 29,847
  • 68
  • 194
  • 309

4 Answers4

24

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
OregonTrail
  • 8,594
  • 7
  • 43
  • 58
  • 1
    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. – kindall Dec 05 '11 at 01:21
  • 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 . . . – O.rka Dec 05 '11 at 01:29
  • I've added some lines to flesh out the example – OregonTrail Dec 05 '11 at 01:30
  • 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()`. – edesz Aug 01 '18 at 15:05
  • ah, good point, try .. else is the way to go here for resiliant execution – OregonTrail Aug 01 '18 at 19:04
5

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.

isedev
  • 18,848
  • 3
  • 60
  • 59
JrBenito
  • 973
  • 8
  • 30
  • I like this better. Is there a version for checking a directory too? – O.rka Mar 30 '16 at 20:43
  • 1
    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. – mlv Mar 31 '16 at 12:54
4

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.

D K
  • 5,530
  • 7
  • 31
  • 45
-1

If you just want to check if a file exists or not, the python os library has solutions for that such as os.path.isfile('TestFile.txt'). OregonTrails answer wouldn't work as you would still need to close the file in the end with a finally block but to do that you must store the file pointer in a variable outside the try and except block which defeats the whole purpose of your solution.