你可以使用os.path.isfile,如果存在,它会返回True.如下:

import os.path
os.path.isfile(fname)

或者使用os.path.exists

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

isfile和exists有一些区别,isfile判断是否是文件,exists判断文件是否存在:

>>> 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

从python3.4开始,pathlib模块提供了类似的方法:

from pathlib import Path
my_file = Path(“/path/to/file”)
if my_file.is_file():