I want to check image is existing on the given path. Code snippet as follows:
if the image exists:
#business logic
else:
#set default logo
I want to check image is existing on the given path. Code snippet as follows:
if the image exists:
#business logic
else:
#set default logo
The most common way to check for the existence of a file in Python is using the exists() and isfile() methods from the os.path module in the standard library.
Using exists:
import os.path
if os.path.exists('mydirectory/myfile.png'):
#business logic
else:
#set default logo
os.path.exists('mydirectory/myfile.png')
returns True if found else
False
Using isfile:
import os.path
if os.path.isfile('mydirectory/myfile.png'):
#business logic
else:
#set default logo
os.path.exists('mydirectory/myfile.png')
returns True if found else
False
Alternatively you can also use try-except as shown below:
try:
f = open('myfile.png')
f.close()
except FileNotFoundError:
print('File does not exist')
You can do this using the os.path.exists()
function in python. So it would be something like -
if os.path.exists('yourdirectory/yourfile.png'):
#business logic
else:
#set default logo
You can also use os.path.isfile()
in a similar manner to check if it is a valid file (os.paath.exists()
will return True
for valid folders as well)