File Open Function with Try & Except Python 2.7.1
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.
O.rka
I am an academic researcher studying machine-learning and microorganisms
Updated on July 24, 2020Comments
-
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 over 12 yearsTo elaborate, the problem identified by OregonTrail is that your
return 0
is indented to the same level as yourif
statement. This puts thereturn
outside theif
, so the function returns0
regardless of whether it got an error or not. -
O.rka over 12 yearshow 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 over 12 yearsI've added some lines to flesh out the example
-
O.rka about 8 yearsI like this better. Is there a version for checking a directory too?
-
mlv about 8 yearsisfile 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 almost 6 yearsThis worked well for me. I used
f = open(fn, "r")
. However, when I used afinally
block to close a file that does not exist, I got the error messageUnboundLocalError: local variable 'f' referenced before assignment
. I could only close the file successfully with anelse
block and not afinally
block - I usedelse: f.close()
. -
OregonTrail almost 6 yearsah, good point, try .. else is the way to go here for resiliant execution