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
3

2 Answers 2

5

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')
    
Sign up to request clarification or add additional context in comments.

Comments

2

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.