1

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
Jason Morse
  • 37
  • 1
  • 4

2 Answers2

3

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')
    
Vinay Kumar
  • 170
  • 1
  • 11
0

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)

Karan Shishoo
  • 2,402
  • 2
  • 17
  • 32