python - 如何检查文件是否存在无异常?

如何在不使用 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

https://stackoverflow.com/questions/82831/

相关文章:

python - 了解切片

python - 如何检查列表是否为空?

python - @staticmethod 和 @classmethod 之间的区别

python - 如何安全地创建嵌套目录?

python - 在 'for' 循环中访问索引

python - Python 的列表方法 append 和 extend 有什么区别?

python - Python 是否有字符串 'contains' 子字符串方法?

python - 如何执行程序或调用系统命令?

python - 如何按值对字典进行排序?

python - 如何列出目录的所有文件?