Searching how to check if a file exists in Python?

File management can become a necessary activity if our code needs to store or retrieve data. Accessing a file can be tricky. This is because our code might assume that the file exists and try to read from or write to it, when in fact, it might not exist. This can lead to your program crashing, and it should be avoided. Fortunately, we can check if a file exists in Python, and avoid such mistakes in our code.

To check if a file exists, we need to tell Python where to look. We do this by specifying the file path. Once we tell python where to look, Python will tell us whether the file is there or not.

There are several ways in which we can check if a file exists. This tutorial will explore some ways.

By using try-except block

The first method we will use is to try opening the file inside a try-except block. If the file does not exist, Python will raise an exception.


try:
    # try to open a file
    # if it does not exist, it will raise an exception
    with open(r'path\to\file.txt') as f:
        print("File exists")

except IOError:
    print("File does not exist")

We actually wrapped the call to function open() with a try block, then reported the failure with the except block. While this method works, Python has other ways we can use to check if a file exists or not.

Using the os module to check if a file exists

The os module provides functionality that allows us to perform many operating system tasks. With this module, we can –

  • Create folders
  • Get the contents of a folder
  • Delete a folder
  • Identify the current working directory
  • Rename a folder or check if a file or folder exists.

Check if a file exists by using the os.path.isfile() method

If we want to check if a particular file exists, we need to import the os module and make us of the path.isfile() method. All we need to do is to pass the suspected path string to the method and check the return boolean value. If the file exists at that location, the value returned will be True, else it will return False.


import os
 
# get the path to the file
path = r'path\to\file.txt'
 
# Check 
if os.path.isfile(path):
    print('File exists')

else:
    print('File does not exist')
Note that we made use of a raw string (prefixing the string with an r) so that Python does not interpret the backslashes as escapes.

Check if a file exists using os.path.exists()

Files and directories have addresses, or paths, by which we can locate them. The exists() method checks if a path, or address, to a file system object exists.

Since exists() checks if a path exists, it can be used to check for the existence of either files or directories (or, folders).

An example is shown below.


import os

# Specify the path to a file system object
path = 'path/to/file.txt'

# Check whether the path, or location
# exists or not
if os.path.exists(path):
    print("Path exists")

else:
    print("Path does not exist")

exists() returns a bool value, just like isfile(). If the path exists, it returns True, otherwise, it returns False.

Using pathlib module to check if a file exists

Another useful module is Python’s pathlib module.

The pathlib module allows us to manipulate filesystem paths without worrying about the operating system we are working on.

The difference between pathlib and os.path lies in the fact that pathlib allows us to work with the path as an object, rather than a string.

Using is_file() method of pathlib.Path

Path instances have an is_file() method that can be used to check for the existence of a file.

It works similarly to isfile() method found in os.path in that, it returns a bool telling us if the path instance is an address for the file object specified when creating the path instance.


# Import Path class from pathlib module
from pathlib import Path
   
# Path relative path
path = r'path\to\file.txt'

# Instantiate the Path class
path_obj = Path(path)
   
# Check if path points to 
# an existing file
if path_obj.is_file():
    print("File exists")

else:
    print("File does not exist")

The main difference between pathlib.Path.is_file() and os.path.isfile() methods is as mentioned earlier; pathlib.Path.is_file() works with a path string as an object, while os.path.isfile() works with paths as strings.

Using pathlib.Path.exists() to check if a file exists

pathlib.Path also has an exists() method that works similarly to the one in os.path.

exists() returns a bool telling us if a path to a file or directory exists.

The difference it has with its os module counterpart is that we need to instantiate a Path object before calling the exists() method on it.


# Import Path class from pathlib module
from pathlib import Path
   
# Path relative path
path = r'path\to\file.txt'

# Instantiate the Path class
path_obj = Path(path)
   
# Check if path points to 
# an existing file or folder
if path_obj.exists():
    print("Path exists")

else:
    print("Path does not exist")

Check if a file exists in a directory or sub-directory

To check if a file exists in a specific directory is similar to finding out if a file exists in a particular path that includes the directory.

The methods os.path.isfile() and pathlib.Path.is_file() can help us check if a file exists in a directory.

The above examples with the methods os.path.isfile() and pathlib.Path.is_file() illustrates this.

Check if a file exists in a sub-directory

The glob module in Python provides functionality that allows searching for files using pattern matching constructs.

We can make use of the glob.glob() function to search for files in a directory or its sub-directories.

The glob.glob() function takes a file path as input and returns a list of files that match the path. An example use of the glob.glob() function is shown below


from glob import glob

path = r"path\to\file.txt"
files = glob(path)

If the file exists in the path specified, glob.glob() returns a list of all matches in the to directory.

What if we needed to carry out our search in sub-directories of the directory to?

glob.glob() has a ** directive that tells the function to search for a match in the sub-directories of the directory specified in the path.

The next example shows how to use the ** directive.


from glob import glob

path = r"path\to\**\file.txt"
files = glob(path)

The search is restricted to child sub-directories of the directory to.

It does not include children of the sub-directories, or descendant sub-directories down the directory tree.

If we need to include all descendant sub-directories of to, we need to make use of the recursive parameter of glob.glob().

By default, recursive has value False. This means that the search will be restricted to child sub-directories of to.

When recursive is set to True, the search is expanded to include the to directory, and the descendant sub-directories of to. the next example shows how to make use of the recursive parameter to search deep into the tree.


from glob import glob

path = r"path\to\**\file.txt"
files = glob(path, recursive=True)

If matches are found, glob.glob() will return a list of all the matches found in the path specified and all of its descendant sub-directories.

Conclusion

We have seen how to check if a file exists in Python. With this knowledge, we can prevent our program from crashing because our program attempted to access a non-existent file.

Thanks for reading our tutorial, and please check our other tutorials on Python such as –

Like this article? Follow us on Facebook and LinkedIn.