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:

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:

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:

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

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.

Get Started With Sentry

Get actionable, code-level insights to resolve Python performance bottlenecks and errors.

  1. Create a free Sentry account

  2. Create a Python project and note your DSN

  3. Grab the Sentry Python SDK

pip install --upgrade sentry-sdk
  1. Configure your DSN
import sentry_sdk sentry_sdk.init( "https://<key><project>", # Set traces_sample_rate to 1.0 to capture 100% # of transactions for performance monitoring. # We recommend adjusting this value in production. traces_sample_rate=1.0, )

Loved by over 4 million developers and more than 90,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.

Share on Twitter
Bookmark this page
Ask a questionJoin the discussion

Related Answers

A better experience for your users. An easier life for your developers.

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