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


当前回答

使用:

import os

# For testing purposes the arguments defaulted to the current folder and file.
# returns True if file found
def file_exists(FOLDER_PATH='../', FILE_NAME=__file__):
    return os.path.isdir(FOLDER_PATH) \
        and os.path.isfile(os.path.join(FOLDER_PATH, FILE_NAME))

它基本上是一个文件夹检查,然后使用 os.path.join 使用适当的目录分离器进行文件检查。

其他回答

它被认为是更好的风格,避免赛车条件。

不要用我的话来支持这个理论,这里有几个:

风格:本课程的“处理异常条件”部分为软件设计(2007) 避免竞赛条件

使用 os.path.isfile() 与 os.access():

import os

PATH = './file.txt'
if os.path.isfile(PATH) and os.access(PATH, os.R_OK):
    print("File exists and is readable")
else:
    print("Either the file is missing or not readable")

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

python -c "import os.path; print os.path.isfile('/path_to/file.xxx')"
if os.path.isfile(path_to_file):
    try:
        open(path_to_file)
            pass
    except IOError as e:
        print "Unable to open file"

提取例外被认为是一个可接受的,和 Pythonic,方法的流量控制在您的程序. 考虑处理错误的文件与 IOErrors. 在这种情况下,一个 IOError 例外将被提取,如果文件存在,但用户没有阅读许可。

来源:使用Python:如何检查是否存在文件

在2016年,最好的方式仍然是使用os.path.isfile:

>>> os.path.isfile('/path/to/some/file.txt')

在Python 3中,您可以使用Pathlib:

import pathlib
path = pathlib.Path('/path/to/some/file.txt')
if path.is_file():
    ...