Read in 4 minutes

last updated 

How to Check if a File or Directory Exists in Python

When 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.

In this tutorial, we’ll show you three different techniques about how to check for a file’s existence.

Check if File Exist

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.

In the following snippet, we are using a simple try-except block. We are trying to open the file filename.txt and if the file doesn’t exist it will raise an exception and it will print “File not accessible”.

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

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

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. Also, it will make 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:

try:
    with open('/etc/hosts') as f:
        print(f.readlines())
        # 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, if you check the existence of the 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.

Check if File Exist using the os.path Module

The os.path module provides some useful functions for working with pathnames. The module is available for both Python 2 and 3.

In the context of this tutorial the most important functions are:

  • os.path.exists(path) - Returns true if the path is a file, directory or a valid symlink.
  • os.path.isfile(path) - Returns true if the path is a regular file or a symlink to a file.
  • os.path.isdir(path) - Returns true if the path is a directory or a symlink to a directory.

The following code will check whether the file filename.txt exist:

import os.path

if os.path.isfile('filename.txt'):
    print ("File exist")
else:
    print ("File not exist")

Use this method if you only want to check whether the file exists or not. If you want to perform an action on the file prefer to use the previous method.

Check if File Exist using the pathlib Module

The pathlib module is available in Python 3.4 and above. This module provides an object-oriented interface for working with filesystem paths for different operating systems.

Same as with the previous example the following code will check whether the file filename.txt exist:

from pathlib import Path

if Path('filename.txt').is_file():
    print ("File exist")
else:
    print ("File not exist")

is_file returns true if the path is a regular file or a symlink to a file. If you want to check for a directory use the is_dir method.

The main difference between pathlib and os.path is that pathlib allows you to work with the paths as Path objects with relevant methods and attributes instead of normal str objects.

If you want to use this module in Python 2 you can install it with pip:

pip install pathlib2

Conclusion

In this guide, we have shown you how to check if a file or directory exists using Python.

If you have any question or feedback, feel free to leave a comment.