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

标签 python file file-exists

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

相关文章:

php - 如何使 php file_exists 使用希腊字符

Java : file exists Vs searching large xml db

python - 带限制的 Matplotlib 对数刻度关闭底部/向上绘图脊柱

以适当的单位返回函数值的 Pythonic 方法

java - <identifier> Java 中的预期编译错误[3]

java - PrintWriter 不保存所有字符

Bash - 文件存在提供不正确的结果

python - 使用 cron 运行 python 脚本

python - 意外的双端队列 python 行为

python - 文件大小是否会影响 python 中写入的性能