我想检查给定路径上是否存在图像。代码片段如下:
if the image exists:
#business logic
else:
#set default logo
在 Python 中检查文件是否存在的最常见方法是使用标准库中 os.path 模块中的 exists(( 和 isfile(( 方法。
-
使用存在:
import os.path if os.path.exists('mydirectory/myfile.png'): #business logic else: #set default logo
如果找到其他内容,则
os.path.exists('mydirectory/myfile.png')
返回 True 假 -
使用 isfile:
import os.path if os.path.isfile('mydirectory/myfile.png'): #business logic else: #set default logo
如果找到其他内容,则
os.path.exists('mydirectory/myfile.png')
返回 True 假 -
或者,您也可以使用 try-except 如下所示:
try: f = open('myfile.png') f.close() except FileNotFoundError: print('File does not exist')
您可以使用 python 中的os.path.exists()
函数来执行此操作。所以它会是这样的——
if os.path.exists('yourdirectory/yourfile.png'):
#business logic
else:
#set default logo
您也可以以类似的方式使用os.path.isfile()
来检查它是否是有效文件(os.paath.exists()
也会返回有效文件夹的True
(