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


当前回答

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

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

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

os.path.isfile(file_path)

其他回答

虽然我总是建议使用尝试和除陈述,这里有几个选项为您(我的个人喜爱是使用os.access):

尝试打开文件:打开文件将始终确认文件的存在. 你可以这样做一个函数: def File_Existence(filepath): f = open(filepath) return True 如果它是错误的,它将停止执行与未经处理的 IOError 或 OSError 在后续版本的 Python. 要捕获例外,你必须使用一个尝试,除了条款。

我还应该提到,有两种方式,你将无法验证一个文件的存在. 无论问题将被拒绝许可或没有这样的文件或目录. 如果你抓住一个IOError,设置IOError为e(如我的第一个选项),然后输入打印(e.args),以便你可以希望确定你的问题. 我希望它有助于! :)

如果文件是要打开的,您可以使用以下技术之一:

with open('somefile', 'xt') as f: # Using the x-flag, Python 3.3 and above
    f.write('Hello\n')

if not os.path.exists('somefile'): 
    with open('somefile', 'wt') as f:
        f.write("Hello\n")
else:
    print('File already exists!')

注意:此查找一个文件或指定的名称的目录。

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

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

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
import os
path = /path/to/dir

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

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