如何检查是否存在文件,而不使用试用声明?


当前回答

您可以使用以下开放方法检查是否存在 + 可阅读的文件:

file = open(inputFile, 'r')
file.close()

其他回答

import os

if os.path.isfile(filepath):
   print("File exists")

使用 os.path.isfile(), os.path.isdir() 和 os.path.exists() 的文件和文件夹进行测试

假设“路径”是有效的路径,此表显示了每个函数为文件和文件夹返回的内容:

此分類上一篇

您还可以测试文件是否是一种特定类型的文件,使用 os.path.splitext() 获取扩展(如果您还不知道)

>>> import os
>>> path = "path to a word document"
>>> os.path.isfile(path)
True
>>> os.path.splitext(path)[1] == ".docx" # test if the extension is .docx
True
import os
os.path.exists(path) # Returns whether the path (directory or file) exists or not
os.path.isfile(path) # Returns whether the file exists or not
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)

不同于 isfile(), exist() 将返回 True for Directory. 因此,根据您是否只需要平板文件或 Directory,您将使用 isfile() 或 exist()。 这里有一些简单的 REPL 输出:

>>> os.path.isfile("/etc/password.txt")
True
>>> os.path.isfile("/etc")
False
>>> os.path.isfile("/does/not/exist")
False
>>> os.path.exists("/etc/password.txt")
True
>>> os.path.exists("/etc")
True
>>> os.path.exists("/does/not/exist")
False