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


当前回答

>>> 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,而不理解它们。

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

其他回答

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

此外, os.access():

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

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

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

使用:

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 使用适当的目录分离器进行文件检查。

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