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


当前回答

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

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

此分類上一篇

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 - posixpath.py (ntpath.py) genericpath.py - 行 ~20+ def exists(path): ""“测试是否有一条路径存在. Returns False for broken symbolic links”"" try: st = os.stat(path) except os.error: return False return True

或:

3、文件系统跨功能

因为这些在文件夹上,(在大多数情况下)它们对我们的问题是无效的(有例外,如非野卡的全球化 - 如 @ShadowRanger指出),所以我不会坚持它们。

os.access("/tmp", os.F_OK)

Linux(Ubuntu(维基百科:Ubuntu版史) 16 x86_64 (pc064)) 也相当于:

笔记:

但是,因为这更像一个工人,我在这里停下来。

6、SysAdmin方法

我认为这是一个(Lame)工作室(gainarie):使用Python作为一个插槽来执行盾牌命令:

底线:

Python 3.4+ 有一个以对象为导向的路径模块: pathlib. 使用这个新模块,您可以检查是否存在这样的文件:

import pathlib
p = pathlib.Path('path/to/file')
if p.is_file():  # or p.is_dir() to see if it is a directory
    # do stuff

在打开文件时,您仍然可以(通常应该)使用尝试/排除区块:

try:
    with p.open() as f:
        # do awesome stuff
except OSError:
    print('Well darn.')

pathlib 模块有很多很好的东西在它:方便的旋转,检查文件的所有者,更容易的路径加入,等等,值得检查。 如果你在更老的 Python (版本 2.6 或更晚),你仍然可以安装 pathlib 带 pip:

# installs pathlib2 on older Python versions
# the original third-party module, pathlib, is no longer maintained.
pip install pathlib2

然后将其输入如下:

# Older Python versions
import pathlib2 as pathlib

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

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

此分類上一篇

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
#Your path here e.g. "C:\Program Files\text.txt"
#For access purposes: "C:\\Program Files\\text.txt"
if os.path.exists("C:\..."):
    print "File found!"
else:
    print "File not found!"

进口 OS 使您更容易与您的操作系统一起导航和执行标准操作。

请参见《如何检查没有例外的文件是否存在》。

如果您需要高级操作,请使用Shutil。