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


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

有很多不同的方法可以检查文件是否存在以及确定它在 Python 中是什么类型的文件。

使用 OS 模块

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

根据文件是否存在,os.path 的两种方法 isfile() 和 exists() 提供值“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 模块

一个名为 Pathlib 的内置面向对象的 Python 接口提供了一个用于处理文件和目录的对象 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

更新于:2022年8月18日

879 次浏览

启动您的 职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.