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


当前回答

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

其他回答

添加一个更轻微的变化,这在其他答案中不完全反映。

这将处理文件_路径是无或空的字符串的情况。

此分類上一篇

def file_exists(file_path):
    if not file_path:
        return False
    elif not os.path.isfile(file_path):
        return False
    else:
        return True

添加基于Shahbaz的建议的变量

def file_exists(file_path):
    if not file_path:
        return False
    else:
        return os.path.isfile(file_path)

添加基于Peter Wood的建议的变量

def file_exists(file_path):
    return file_path and os.path.isfile(file_path):

使用 os.path.exist 查看文件和目录:

import os.path
os.path.exists(file_path)

使用 os.path.isfile 仅查看文件(注:以下是符号链接):

os.path.isfile(file_path)
import os
path = /path/to/dir

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

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

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

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

>>> from pathlib import Path
>>> Path('/').is_file()
False
>>> Path('/initrd.img').is_file()
True
>>> Path('/doesnotexist').is_file()
False

>>> import os
>>> os.path.isfile('/')
False
>>> os.path.isfile('/initrd.img')
True
>>> os.path.isfile('/doesnotexist')
False

现在上面的可能是最好的实用直接答案在这里,但有可能有一个竞赛条件(取决于你正在尝试实现什么),并且事实上,基础实施使用一个尝试,但Python使用尝试到处在其实施。

更长、更有趣的答案

>>> from pathlib import Path
>>> root = Path('/')
>>> root.exists()
True

>>> root.is_file()
False

is_file(self)
    Whether this path is a regular file (also True for symlinks pointing
    to regular files).

>>> import tempfile
>>> file = tempfile.NamedTemporaryFile()
>>> filepathobj = Path(file.name)
>>> filepathobj.is_file()
True
>>> filepathobj.exists()
True

>>> del file
>>> filepathobj.exists()
False
>>> filepathobj.is_file()
False

def is_file(self):
    """
    Whether this path is a regular file (also True for symlinks pointing
    to regular files).
    """
    try:
        return S_ISREG(self.stat().st_mode)
    except OSError as e:
        if e.errno not in (ENOENT, ENOTDIR):
            raise
        # Path doesn't exist or is a broken symlink
        # (see https://bitbucket.org/pitrou/pathlib/issue/12/)
        return False

from contextlib import suppress
from pathlib import Path

>>> with suppress(OSError), Path('doesnotexist').open() as f:
...     for line in f:
...         print(line)
... 
>>>
>>> with suppress(OSError):
...     Path('doesnotexist').unlink()
... 
>>> 

class suppress(object):
    def __init__(self, *exceptions):
        self.exceptions = exceptions
    def __enter__(self):
        return self
    def __exit__(self, exc_type, exc_value, traceback):
        if exc_type is not None:
            return issubclass(exc_type, self.exceptions)

from contextlib import contextmanager

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

import os
os.path.isfile(path)

>>> OSError is os.error
True

try:
    with open(path) as f:
        f.read()
except OSError:
    pass

import os
os.access(path, os.F_OK)

批评另一个答案:

另一个答案是关于os.access:

这个答案说,它更喜欢一个非皮顿,错误的方法,没有理由,似乎鼓励用户使用低级的API,而不理解它们。

它还创建了一个背景管理器,通过无条件返回真相,允许所有例外(包括键盘中断和系统输出!)沉默地通过,这是一个很好的方式来隐藏错误。