如果您正在检查的原因是这样你就可以做这样的事情if file_exists: open_it()它的安全使用try围绕试图打开它。检查然后打开风险,删除或移动文件或检查时以及尝试打开文件时。 
如果您不打算立即打开文件,可以使用os.path.isfile 
如果 path 是现有常规文件,则返回
True。这遵循符号链接,因此对于相同的路径, islink()和isfile()都可以为 true。
import os.path
os.path.isfile(fname)如果你需要确定它是一个文件。
从 Python 3.4 开始, pathlib模块提供了一种面向对象的方法(在 Python 2.7 中向后移植到pathlib2 ): 
from pathlib import Path
my_file = Path("/path/to/file")
if my_file.is_file():
    # file exists要检查目录,请执行以下操作:
if my_file.is_dir():
    # directory exists要检查Path对象是否存在,无论它是文件还是目录,请使用exists() : 
if my_file.exists():
    # path exists您还可以在try块中使用resolve() : 
try:
    my_abs_path = my_file.resolve()
except FileNotFoundError:
    # doesn't exist
else:
    # exists你有os.path.exists函数: 
import os.path
os.path.exists(file_path)这会为文件和目录返回True ,但您可以改为使用
os.path.isfile(file_name)测试它是否是一个特定的文件。它遵循符号链接。
与isfile()不同, exists()将为目录返回True 。 
因此,根据您是否只需要普通文件或目录,您将使用isfile()或exists() 。这是一个简单的 REPL 输出。 
>>> print os.path.isfile("/etc/password.txt")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/password.txt")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False