如何检查文件是否存在而不引发异常?

2024-03-29 10:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如果不使用^{}语句,如何查看文件是否存在?


Tags: 文件语句
3条回答

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

如果不打算立即打开文件,可以使用^{}

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开始,^{} 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块中使用resolve(strict=True)

try:
    my_abs_path = my_file.resolve(strict=True)
except FileNotFoundError:
    # doesn't exist
else:
    # exists

^{}不同,^{}将返回目录的True
因此,根据您是否只需要普通文件或目录,您将使用isfile()exists()。这是一个简单的REPL输出。

>>> print os.path.isfile("/etc/password.txt")
True
>>> print os.path.isfile("/etc")
False
>>> print os.path.isfile("/does/not/exist")
False
>>> print os.path.exists("/etc/password.txt")
True
>>> print os.path.exists("/etc")
True
>>> print os.path.exists("/does/not/exist")
False

您有^{}函数:

import os.path
os.path.exists(file_path)

这将返回文件和目录的True,但是您可以使用

os.path.isfile(file_path)

测试它是否是一个特定的文件。它遵循符号链接。

相关问题 更多 >