前言
在下载文件之前需判断文件是否已存在,如果已经存在就不重复下载了
实现方式
在Python中,可以使用os模块中的path.exists()
函数来判断文件是否存在。以下是两种不同的实现方法:
方法一:使用os模块中的path.exists()
函数
import os
def file_exists(file_path):
return os.path.exists(file_path)
方法二:使用try-except
语句捕获文件的打开异常
def file_exists(file_path):
try:
with open(file_path):
pass
return True
except FileNotFoundError:
return False
上述两种方法都能判断文件是否存在,方法一直接使用path.exists()
函数返回值,方法二通过尝试以打开文件的方式判断是否存在,并在捕获FileNotFoundError
异常时返回False
。