如果你要检查的原因是可以执行类似的操作if file_exists: open_it()
,则try
尝试使用a
来打开它会更安全。检查然后打开可能会导致文件被删除或移动,或者介于检查和尝试打开文件之间。
如果你不打算立即打开文件,则可以使用 os.path.isfile
True如果path是现有的常规文件,则返回。这遵循符号链接,因此,对于同一路径,islink()
和isfile()
都可以为true
。
import os.path
os.path.isfile(fname)
如果你需要确保它是一个文件。
从Python 3.4开始,该pathlib模块提供了一种面向对象的方法(pathlib2在2.7中向后移植):
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
你也可以resolve(strict=True)在一个try块中使用:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists