hen writing Python scripts, you may want to perform a certain action only if a file or directory exists or not. For example, you may want to read or write data to a configuration file or to create the file only if it already doesn’t exist.

In Python, there are many different ways to check whether a file exists and determine the type of the file.

This tutorial shows three different techniques about how to check for a file’s existence.

Check if File Exists

The simplest way to check whether a file exists is to try to open the file. This approach doesn’t require importing any module and works with both Python 2 and 3. Use this method if you want to open the file and perform some action.

The following snippet is using a simple try-except block. We are trying to open the file filename.txt, and if the file doesn’t exist, an IOError exception is raised and “File not accessible” message is printed:

    f = open("filename.txt")
    # Do something with the file
except IOError:
    print("File not accessible")

If you are using Python 3, you can also use FileNotFoundError instead of IOError exception.

When opening files, it is recommended to use the with keyword, which makes sure the file is properly closed after the file operations are completed, even if an exception is raised during the operation. It also makes your code shorter because you do not need to close the file using the close function.

The following code is equivalent to the previous example:

    with open('/etc/hosts') as f:
        # Do something with the file
except IOError:
    print("File not accessible")

In the examples above, we were using the try-except block and opening the file to avoid the race condition. Race conditions happen when you have more than one process accessing the same file.

For example, when you check the existence of a file another process may create, delete, or block the file in the timeframe between the check and the file opening. This may cause your code to break.


How to Check if a File or Directory Exists in Python
1.20 GEEK