如何在不使用 try
的情况下检查文件是否存在声明?
最佳答案
如果您检查的原因是您可以执行类似 if file_exists: open_it()
之类的操作,那么在尝试打开它时使用 try
会更安全.检查然后打开文件可能会导致文件被删除或移动,或者在检查和尝试打开文件之间存在风险。
如果您不打算立即打开文件,可以使用 os.path.isfile
Return
True
if path is an existing regular file. This follows symbolic links, so both islink() and isfile() can be true for the same path.
import os.path
os.path.isfile(fname)
如果你需要确定它是一个文件。
从 Python 3.4 开始,pathlib
module提供面向对象的方法(在 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
block 中使用 resolve(strict=True)
:
try:
my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
# doesn't exist
else:
# exists
关于python - 如何检查文件是否存在无异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/82831/