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


当前回答

这里是一个单线的Python命令为Linux命令线环境,我觉得这是非常有用的,因为我不是那么热的Bash男孩。

python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"

其他回答

import os

if os.path.isfile(filepath):
   print("File exists")
import os
path = /path/to/dir

root,dirs,files = os.walk(path).next()
if myfile in files:
   print "yes it exists"

这在检查多个文件时是有用的,或者你想与现有列表进行一组交叉/分解。

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

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

在2016年,这仍然是最容易的方式来检查是否有文件和是否是文件:

import os
os.path.isfile('./file.txt')    # Returns True if exists, else False

isfile 实际上只是一个内部使用 os.stat 和 stat.S_ISREG(模式) 的辅助方法. 这个 os.stat 是一种低级别的方法,将为您提供有关文件、目录、插件、插件等的详细信息。

注意: 然而,这种方法不会以任何方式锁定文件,因此您的代码可能会受到“检查到使用时间”(TOCTTOU)错误的脆弱性。

因此,提取例外被认为是一个可接受的,和 Pythonic,方法的流量控制在您的程序. 一个人应该考虑处理失去的文件与IOErrors,而不是如果声明(只是一个建议)。

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)