如何在不使用try语句的情况下检查文件是否存在?
如何在不使用try语句的情况下检查文件是否存在?
-
如果您检查的原因是为了您可以执行类似的操作
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