Python 如何检查文件是否存在
您可能希望在Python脚本中仅在文件或目录存在或不存在时执行特定操作。例如,您可能希望从配置文件中读取或写入,或者仅在文件不存在时才创建该文件。
在Python中,有许多不同的方法可以检查文件是否存在并确定它是什么类型的文件。
使用OS模块
一个内置的Python模块称为OS具有处理操作系统的工具。我们可以通过使用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模块
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
极客笔记