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 am trying to make a function that checks if a file exists, and if not, it should print an error message and return 0. Why does this not work?

+6
source share
4 answers

You will need to defer return 0 if you want to return from the except block. Also, your argument does nothing. Instead of assigning a file descriptor to it, I assume that you want this function to be able to test any file? If not, you do not need 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 
+17
source

This is most likely because you want to open the file in read mode. Replace β€œU” with β€œr”.

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

+3
source

I think os.path.isfile() better if you just want to β€œcheck” if the file exists, since you don't really need to open the file. In any case, after opening it is recommended to consider closing the file, and the above examples do not include this.

+2
source

If you just want to check if a file exists or not, there are solutions for this in the python os library, such as os.path.isfile('TestFile.txt') . OregonTrails answer will not work, since you still need to close the file at the end using the finally block, but for this you need to save the file pointer in a variable outside the try block and with an exception, which contradicts the whole purpose of your solution.

0
source

Source: https://habr.com/ru/post/1384629/


All Articles