DEV Community

Cover image for How to Check if a File Exists in Python
Jeremy Grifski
Jeremy Grifski

Posted on • Updated on • Originally published at therenegadecoder.com

How to Check if a File Exists in Python

As someone who literally just learned about canonical URLs and cross-posting, I figured I'd give it a try on dev.to with one of my more popular articles. I hope you like it!

Problem Introduction

Recently, I was looking to read some data from a configuration file, but I wanted the code to be backwards compatible. In other words, if the configuration file didn’t exist, I wanted to assume the original preset values. Otherwise, I would pull the data from the configuration file.

Fortunately, I did my research and came up with a solution. The plan was to check to see if the configuration file existed. If it did, the program would read from it and populate the necessary fields. Otherwise, the program would lean back on some arbitrary preset values.

To do that though, I had to find a way to verify the existence of a file. As it turns out, there are plenty of ways to do that in Python.

Solutions

If we’re looking to check if a file exists, there are a few solutions:

  • Check if a file exists with a try/except block (Python 2+)
  • Check if a file exists using os.path (Python 2+)
  • Check if a file exists using the Path object (Python 3.4+)

Of course, it’s up to us to determine which solution is the best for us!

Check if a File Exists with a Try Block

Up first on the list is a try-except block. In this scenario, we would attempt to open our file in the try block. If the file fails to open, we run the preset values. For example:

try:
    fh = open('/path/to/file', 'r')
    # Store configuration file values
except FileNotFoundError:
    # Keep preset values
Enter fullscreen mode Exit fullscreen mode

This solution is perhaps the simplest and most robust, but the FileNotFoundError is an update from Python 3. You’ll have more trouble with catching an IOError in Python 2.

Check if a File Exists with OS Path

Another option is to skip error handling altogether and directly verify that the path exists. For example:

import os
exists = os.path.isfile('/path/to/file')
if exists:
    # Store configuration file values
else:
    # Keep presets
Enter fullscreen mode Exit fullscreen mode

Of course, the drawback here is the race condition from line 2 to line 3. If for some reason the configuration file gets deleted between line 2 and line 3, then the script will crash. If that’s not a risk in your application, then this solution is great.

Check if a File Exists with a Path Object

If you’re obsessed with object-oriented programming like me, then maybe this solution is for you. As of Python 3.4, we can wrap our file reference in an object which brings along a host of new functionality. For example:

from pathlib import Path
config = Path('/path/to/file')
if config.is_file():
    # Store configuration file values
else:
    # Keep presets
Enter fullscreen mode Exit fullscreen mode

In addition, this new object representation allows us to use our original try-except block:

try:
    absolute_path = config.resolve()
    # Store configuration file values
except FileNotFoundError:
    # Keep presets
Enter fullscreen mode Exit fullscreen mode

Of course, you may not need all this functionality. After all, if reading the contents is the goal, then the first option is probably the best.

A Little Recap

Using the methods above, we have several options to check if a file exists in Python:

# Brute force with a try-except block
try: 
    fh = open('/path/to/file', 'r') 
except FileNotFoundError: 
    pass

# Leverage the OS package
import os 
exists = os.path.isfile('/path/to/file')

# Wrap the path in an object for enhanced functionality
from pathlib import Path
config = Path('/path/to/file') 
if config.is_file(): 
    pass
Enter fullscreen mode Exit fullscreen mode

For the purposes of this tutorial, we were only interested in files. However, these solutions can be adapted to verify the existences of directories and symbolic links, so don’t be afraid to play around. That’s the beauty of Python!

At any rate, thanks for taking the time to check out this article. If it’s your first time here and you found this article helpful, why not subscribe to The Renegade Coder? Subscription is free, and you’ll always be up to date with the latest content.

See you next time!

Top comments (1)

Collapse
 
lokesh1729 profile image
Lokesh Sanapalli

os.path.exists