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


当前回答

此外, os.access():

if os.access("myfile", os.R_OK):
    with open("myfile") as fp:
        return fp.read()

是 R_OK, W_OK, 和 X_OK 旗帜测试许可证(doc)。

其他回答

你可以写布莱恩的建议,没有尝试:

from contextlib import suppress

with suppress(IOError), open('filename'):
    process()

suppress 是 Python 3.4 的组成部分。在旧版本中,您可以快速写下自己的 suppress:

from contextlib import contextmanager

@contextmanager
def suppress(*exceptions):
    try:
        yield
    except exceptions:
        pass

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

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

使用 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")

要检查是否存在文件,

from sys import argv

from os.path import exists
script, filename = argv
target = open(filename)
print "file exists: %r" % exists(filename)

在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():
    ...