Sentry Answers>Python>

How do I check whether a file exists without exceptions?

How do I check whether a file exists without exceptions?

Valerie M.

The Problem

It is common practice to raise exceptions, especially when handling files. This practice is useful as it allows you to anticipate any errors that may occur during normal code execution instead of ignoring them.

You can also provide the user with useful feedback in case something goes wrong.

When working with files, it is useful to check if a file exists, and handle exceptions before you decide to do anything to it such as deleting or editing it.

A typical example of doing this is:

Click to Copy
my_file = "path/to/file" try: f = open(my_file, "w") except IOError: print("No such file: " + my_file)

On the other hand, sometimes you want to write a simple file-processing program without worrying about catching all exceptions. In such cases, how can you check whether a file exists without using exceptions?

The Solution

There are several ways to check whether a file exists without using exceptions.

We’re going to consider a couple of possible alternatives: using the os.path or pathlib modules.

Using os.path

You can use the os.path.exists() method:

Click to Copy
import os os.path.exists("path/to/file")

The above method returns either True or False depending on whether the file exists.

Using pathlib

The pathlib module could also be used:

Click to Copy
from pathlib import Path my_file = Path("/path/to/file") if my_file.is_file(): print("It lives!")

is_file() returns True or False depending on whether the file exists.

This module is an Object-Oriented approach to file processing where you instantiate a Path object and pass it the file name. This approach is useful because it provides access to different file processing functionality in one place, which is an easier and more readable alternative to the standard os.path library.

Furthermore, pathlib “offers classes representing filesystem paths with semantics appropriate for different operating systems” (Python Docs).

It’s important to note that pathlib is available since Python 3.4. As such, to run the file in a system that also supports Python 2, you may need to specify the appropriate Python version to use, e.g. python3 check_file_exists.py.

While the pathlib module is newer, it doesn’t necessarily mean that it’s better than using os. According to the Python Docs, “the os.path module is always the path module suitable for the operating system Python is running on, and therefore usable for local paths”. As a result, you would use it if you’re writing programs that perform low-level string manipulation. This article provides a comparative analysis of when you would use either module.

  • Sentry BlogPython Performance Testing: A Comprehensive Guide
  • Syntax.fmListen to the Syntax Podcast
  • Sentry BlogLogging in Python: A Developer’s Guide
  • Syntax.fm logo
    Listen to the Syntax Podcast

    Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.

    SEE EPISODES

Considered “not bad” by 4 million developers and more than 100,000 organizations worldwide, Sentry provides code-level observability to many of the world’s best-known companies like Disney, Peloton, Cloudflare, Eventbrite, Slack, Supercell, and Rockstar Games. Each month we process billions of exceptions from the most popular products on the internet.

© 2024 • Sentry is a registered Trademark
of Functional Software, Inc.