O.rka
O.rka

Reputation: 30687

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???

Upvotes: 11

Views: 117622

Answers (4)

Hamid Haris
Hamid Haris

Reputation: 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.

Upvotes: -1

JrBenito
JrBenito

Reputation: 1003

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.

Upvotes: 5

D K
D K

Reputation: 5760

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.

Upvotes: 4

OregonTrail
OregonTrail

Reputation: 9039

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

Upvotes: 27

Related Questions