File Open Function with Try & Except Python 2.7.1

后端 未结 4 939
不知归路
不知归路 2020-12-07 02:46
def FileCheck(fn):       
       try:
           fn=open(\"TestFile.txt\",\"U\") 
       except IOError: 
           print \"Error: File does not appear to exist.\"
         


        
4条回答
  •  死守一世寂寞
    2020-12-07 03:08

    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.

提交回复
热议问题