How do I check whether a file exists without exceptions?

后端 未结 30 1862
北海茫月
北海茫月 2020-11-21 05:07

How do I check if a file exists or not, without using the try statement?

30条回答
  •  情书的邮戳
    2020-11-21 05:17

    import os.path
    
    def isReadableFile(file_path, file_name):
        full_path = file_path + "/" + file_name
        try:
            if not os.path.exists(file_path):
                print "File path is invalid."
                return False
            elif not os.path.isfile(full_path):
                print "File does not exist."
                return False
            elif not os.access(full_path, os.R_OK):
                print "File cannot be read."
                return False
            else:
                print "File can be read."
                return True
        except IOError as ex:
            print "I/O error({0}): {1}".format(ex.errno, ex.strerror)
        except Error as ex:
            print "Error({0}): {1}".format(ex.errno, ex.strerror)
        return False
    #------------------------------------------------------
    
    path = "/usr/khaled/documents/puzzles"
    fileName = "puzzle_1.txt"
    
    isReadableFile(path, fileName)
    

提交回复
热议问题