小编典典

如何在不使用try语句的情况下检查文件是否存在?

python

如何在不使用try语句的情况下检查文件是否存在?


阅读 232

收藏
2022-01-04

共1个答案

小编典典

如果您检查的原因是为了您可以执行类似的操作if file_exists: open_it(),则使用 atry来尝试打开它会更安全。检查然后打开可能会导致文件被删除或移动,或者在您检查和尝试打开它之间发生某些事情。

如果您不打算立即打开文件,则可以使用 os.path.isfile

True如果路径是现有的常规文件,则返回。这遵循符号链接,因此islink()isfile()对于同一路径都可以为真。

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

如果你需要确定它是一个文件。

从 Python 3.4 开始,该pathlib模块提供了一种面向对象的方法(pathlib2在 Python 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
2022-01-04