如何在不抛出异常的情况下检查文件是否存在?
41 个回答
1230
跟 isfile() 不一样,exists() 会对文件夹也返回 True。所以,如果你只想检查普通文件,或者想同时检查文件和文件夹,就要选择使用 isfile() 或者 exists()。下面是一些简单的 REPL 输出示例:
>>> os.path.isfile("/etc/password.txt")
True
>>> os.path.isfile("/etc")
False
>>> os.path.isfile("/does/not/exist")
False
>>> os.path.exists("/etc/password.txt")
True
>>> os.path.exists("/etc")
True
>>> os.path.exists("/does/not/exist")
False
2616
使用 os.path.exists 可以检查文件和文件夹是否存在:
import os.path
os.path.exists(file_path)
使用 os.path.isfile 只检查文件是否存在(注意:这个方法会跟随 符号链接):
os.path.isfile(file_path)
6551
如果你检查文件的原因是想做类似 if file_exists: open_it() 的事情,那么在尝试打开文件时最好用 try 来包裹一下。因为在你检查文件存在与否和实际打开文件之间,文件可能被删除、移动或者发生其他变化,这样就会出问题。
如果你不打算立即打开文件,可以使用 os.path.isfile 来检查。
如果路径是一个存在的普通文件,它会返回
True。这个方法会跟随符号链接,所以对于同一个路径,islink() 和 isfile() 都可能返回真。
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(strict=True):
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists