如何使用 Python 检查文件是否存在?

programmingpythonserver side programming更新于 2025/3/22 19:24:17

您可能希望仅在文件或目录存在或不存在的情况下在 Python 脚本中执行特定操作。例如,您可能希望读取或写入配置文件,或者仅在文件不存在时创建文件

在 Python 中,有很多不同的方法可以检查文件是否存在并确定其类型。

使用 OS 模块

内置的 Python 模块 Os 具有处理操作系统的工具。我们可以使用 os 访问操作系统功能。在 Python 中,os.path 是 os 的子模块。这用于更改公共路径的名称。

根据文件是否存在,os.path 的两个方法 isfile() 和 exist() 提供值"True"或"False"。

os.path.isfile() 方法

此方法确定指定路径是否已包含常规文件。

语法

os.path.isfile(filepath)

其中,filepath 表示文件的路径。

返回类型取决于文件是否存在,"True"或"False"。

示例

以下是使用 os.path.isfile() 方法检查文件是否存在的示例 -

import os filepath= 'C:\Users\Lenovo\Downloads\Work TP\trial.py' doesFileExists = os.path.isfile(filepath) print (doesFileExists)

输出

以下是根据文件是否存在对上述代码的输出 -

True

os.path.exists() 方法

此方法检查给定的路径是否存在。

语法

os.path.exists(filepath)

其中,filepath 表示文件的路径。

返回类型取决于文件是否存在,"True"或"False"。

示例

以下是使用 os.path.exists() 方法检查文件是否存在的示例 -

import os filepath= 'C:\Users\Lenovo\Downloads\Work TP\trial.py' doesFileExists = os.path.exists(filepath) print(doesFileExists)

输出

以下是根据文件是否存在对上述代码的输出 -

True

使用 pathlib 模块

Python 内置的面向对象接口 Pathlib 提供了用于处理文件和目录的对象 API。pathlib 模块提供了两个用于确定文件是否存在的选项,类似于 os 模块。

示例 - pathlib.path.exists() 方法

以下是使用 pathlib.path.exists() 方法检查文件是否存在的示例 -

import pathlib filepath = pathlib.Path("C:\Users\Lenovo\Downloads\Work TP\trials.py") if filepath.exists(): print ("The given file exists") else: print ("The given file does not exists")

输出

以下是根据文件是否存在对上述代码的输出 -

The given file does not exists

示例 - pathlib.is_file() 方法

以下是使用 pathlib.is_file() 方法检查文件是否存在的示例 -

import pathlib filepath = pathlib.Path("C:\Users\Lenovo\Downloads\Work TP\trial.py") if filepath.is_file(): print ("The given file exists") else: print ("The given file does not exists")

输出

以下是根据文件是否存在对上述代码的输出 -

The given file exists

使用 Glob 模块

使用通配符,glob 模块用于查找文件名符合特定模式的文件。这还提供"True"或"False"值来指示文件是否存在。

示例

以下是使用 glob 模块检查文件是否存在的示例 -

import glob if glob.glob(r"C:\Users\Lenovo\Downloads\Work TP\trial.py"): print ("The given file exists") else: print("The given file does not exists")

输出

以下是根据文件的存在情况对上述代码进行的输出 -

The given file exists

异常处理方法

我们在 try 和 except 语句中的"try"下编写了代码,"except"语句检查"try"下的代码是否存在错误。如果发现任何错误,则执行"except"块。因此,我们使用"try"语句打开文件并确定它是否存在。如果文件丢失,则会出现 IOError 异常,这使我们能够打印输出并显示文件丢失。

使用"test -e",第一步是确认文件路径有效。如果路径有效,我们使用"test -f"或"test -d"来确定文件是否存在。

示例 - 1

以下是使用异常处理方法 (IOError) 检查文件是否存在的示例 -

try: file = open('C:\Users\Lenovo\Downloads\Work TP\trial.py') print("The given file exists") file.close() except IOError: print("The given file does not exists")

输出

以下是根据文件的存在情况对上述代码进行的输出 -

The given file exists

示例 - 2

以下是使用异常处理方法 (FileNotFoundError) 检查文件是否存在的示例 −

try: file = open('C:\Users\Lenovo\Downloads\Work TP\trials.py') print("The given file exists") file.close() except FileNotFoundError: print("The given file does not exists")

输出

以下是根据文件的存在情况对上述代码进行的输出。

The given file does not exists

相关文章


有用资源