Valerie M.
—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?
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.
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.
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 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.
Tasty treats for web developers brought to you by Sentry. Get tips and tricks from Wes Bos and Scott Tolinski.
SEE EPISODESConsidered “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.
Here’s a quick look at how Sentry handles your personal information (PII).
×We collect PII about people browsing our website, users of the Sentry service, prospective customers, and people who otherwise interact with us.
What if my PII is included in data sent to Sentry by a Sentry customer (e.g., someone using Sentry to monitor their app)? In this case you have to contact the Sentry customer (e.g., the maker of the app). We do not control the data that is sent to us through the Sentry service for the purposes of application monitoring.
Am I included?We may disclose your PII to the following type of recipients:
You may have the following rights related to your PII:
If you have any questions or concerns about your privacy at Sentry, please email us at compliance@sentry.io.
If you are a California resident, see our Supplemental notice.