close

How do I handle the exception if one or two files don’t exist?

Hello Guys, How are you all? Hope You all Are Fine. Today We Are Going To learn about How do I handle the exception if one or two files don’t exist in Python. So Here I am Explain to you all the possible Methods here.

Without wasting your time, Let’s start This Article.

Table of Contents

How do I handle the exception if one or two files don’t exist?

  1. How do I handle the exception if one or two files don't exist?

    I don't know the scenario of the author. If you want to just stop the function, you can use return False. But if you still want to execute some function even the file1 and file2 doesn't exists, you can use pass to ignore the exception.

  2. handle the exception if one or two files don't exist

    I don't know the scenario of the author. If you want to just stop the function, you can use return False. But if you still want to execute some function even the file1 and file2 doesn't exists, you can use pass to ignore the exception.

Method 1

If you don’t want to use os.path.exists() or os.path.isfile() from the built-in os.path module, you’ll have to use two try-except blocks:

def check_files_if_exists(...):
    try:
        f1 = open(...)
        f1.close()
    except:
        return False # Return False because the path doesn't exist
    try:
        f2 = open(...)
        f2.close()
    except:
        return False # Return False because the path doesn't exist
    return True # This only occurs when both files exist.

Method 2

def check_files_if_exist():
    try:
        f1 = open(file1)
        f1.close()
        f2 = open(file2)
        f2.close()
    except:
        pass  # if you want to stop the whole function, you can use "return False" here.

I don’t know the scenario of the author. If you want to just stop the function, you can use return False. But if you still want to execute some function even the file1 and file2 doesn’t exists, you can use pass to ignore the exception.

Summery

It’s all About this issue. Hope all Methods helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which Method worked for you? Thank You.

Also, Read