Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 946
O.rka Avatar asked Dec 05 '11 01:12

O.rka


People also ask

Which function opens file?

The open() function opens a file, and returns it as a file object. Read more about file handling in our chapters about File Handling.

How does Python handle file open error?

Since Python can not find the file, we are opening it creates an exception that is the FileNotFoundError exception. In this example, the open() function creates the error. To solve this error, use the try block just before the line, which involves the open() function: filename = 'John.

Can you open a file in a function Python?

Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as it is used to read or modify the file accordingly. We can specify the mode while opening a file. In mode, we specify whether we want to read r , write w or append a to the file.


2 Answers

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
like image 185
OregonTrail Avatar answered Sep 29 '22 10:09

OregonTrail


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.

like image 42
D K Avatar answered Sep 29 '22 12:09

D K