In this tutorial, you’ll learn how to use Python to check if a file or a directory exists. Being able to work with files is an important skill for someone using Python at any skill level. Being able to check if a file or a directory exists, in particular, allows us to run our code safely – thereby preventing accidental program crashes.
Python provides a wide array of options for interacting with your operating system. Because of this, you’ll learn a number of different ways to use Python to check if a file or a directory exists. By the end of this tutorial, you’ll have learned how to use the os
and the pathlib
modules, and how these approaches differ.
Check out some other tutorials, such as how to copy a file using Python, or how to use Python to delete a file.
The Quick Answer: Use pathlib .exists()
Library | Function / Method | Checks |
---|---|---|
pathlib | Path.is_file() | File |
pathlib | Path.is_dir() | Directory |
pathlib | Path.exists() | File / Directory |
os | path.isfile() | File |
os | path.isdir() | Directory |
os | path.exists() | File / Directory |
In the next sections, you’ll learn how to use the two libraries and their functions / methods to check if a file or a directory exists.
Table of Contents
File Path Differences Between Windows, Mac OS, and Linux
Before we dive into the tutorial, let’s cover off some key distinctions between how file paths are handled in Windows, Mac OS and Linux. In all of our examples, we’ll use strings
to store our paths. This has significant impacts when we’re using paths that contain multiple directories. Before we dive into these impacts, let’s see how the different operating systems store file paths:
- Directories in Mac OS and Linux are separated with a / character.,
- Directories in Windows are separated with a
\
character
Why does this matter? Python interprets the \
character as an escape character, meaning that the character following the escape character is ignored. Because the \
character has a real, “literal” meaning in a Window file path, we will want to treat it as a real character.
Because of this, when we use Windows file paths, we will create a raw string. We can accomplish this by prepending the string with the letter r
. We could also use \\
to escape each of our forward slashes, but converting the string to a raw string is much simpler.
If you’re using Windows, simply prepend a r
to your string for each of the examples in this tutorial. This will convert the string to a raw-string, allowing each character (including the \
) to be interpreted literally. The examples in this tutorial, will not work without this.
Check if a File Exists Using try and except
If you simply want to prevent your program from crashing when you try to, say, open a file, one of the easiest ways to accomplish this is to simply wrap everything in a try... except
block.
With these types of blocks, we can try to perform an action, such as opening a file. We perform actions within this block, unless an exception is found. In particular, a FileNotFoundError
is raised when a given file doesn’t exist.
Let’s see how we can safely perform this:
try:
except FileNotFoundError:
pass
We can see here that simply doing this will allow the code to safely continue running if the file doesn’t exist. If the file does exist, then it allows us to process it in whichever way we may want to.
Using Python 2.7? The FileNotFoundError
was only introduced in Python 3. If you want or need your code to be backwards compatible, then use the IOError
in your except
statement. The FileNotFoundError
actually subclasses the IOError
, meaning it would still catch the file not being found.
Understanding the Python Pathlib Library
The Python pathlib library uses an object-oriented approach to file paths. This is a great approaches as it simply allows us to create a Path
object, which we can then use throughout our code. Because the module comes with a number of object methods and attributes, we can easily check, for example, if a file or directory exists.
The pathlib
module was introduced in Python 3.4. Because of this, if you’re running an old version of Python, be sure to check out the section on the os
library below.
Let’s begin by loading the Python pathlib module, including its Path
object:
from pathlib import Path
Once we’ve done this, we can create a Path object by passing in a file path. Let’s create a Path object and check its type using the built-in type()
function.
# Creating a Path object
from pathlib import Path
file_path = Path('/Users/datagy/Documents/app.py')
print(type(file_path))
# Returns: <class 'pathlib.PosixPath'>
We can see that this returns a pathlib object! Now that we have this object, we’re able to manipulate it in different ways or even check its attributes.
Check out my video below to see how you can use Pathlib to organize your files:
Use Python Pathlib to Check if a File Exists
Now that you’ve had a bit of an overview of what the Python pathlib module is, let’s begin taking a look at how we can use it to check if a file exists. As mentioned in the previous section, the Pathlib module takes an object-oriented approach to file paths. Because of this, we can use various attributes to learn more about our Path object.
One of these attributes is the .is_file()
method, which is used to evaluate whether a Path object evaluates to a file. If the object points to a file, then the method will return True
. Otherwise, the method returns False
.
Let’s see how we can use the .is_file()
method to check if a file exists:
# Creating a Path object
from pathlib import Path
file_path = Path('/Users/datagy/Documents/app.py')
# Checking if a file exists with Pathlib
print(file_path.is_file())
# Returns: True if a file exists, False if a file doesn't exist
Similarly, we can use this method in a conditional if
statement. For example, we can use it to first check if a file exists and then do some actions.
# Checking if a file exists with Pathlib
if file_path.is_file():
Here we use a conditional if
to check if a file exists before completing other actions. Because the method returns a boolean value, we can simply use the implied truthy-ness of is statement. This means that if a file doesn’t exist, then it will return False
, indicating to the if statement to not continue.
Use Python Pathlib to Check if a Directory Exists
Similar to the Pathlib .is_file()
method, Pathlib also comes with a method that checks if a path points to an existing directory. This method is called the .is_dir()
method, which evaluates to True
if the path points to a directory and that directory exists.
When we create a Path
object with a file path, we can use the .is_dir()
method to check if a directory exists.
Let’s see how this works in Python:
# Creating a Path object
from pathlib import Path
file_path = Path('/Users/datagy/Documents/')
# Checking if a directory exists with Pathlib
print(file_path.is_dir())
# Returns: True
This looks very similar to the method for checking if a file exists, except that we pass a directory into the object, rather than a file. If a directory doesn’t exist, then the method will return False
.
Use Python Pathlib to Check if a File or a Directory Exists
Pathlib also comes with an intuitive way to check if either a file or directory exists, regardless of its type. The benefit of this approach is that it’s all encompassing. The other methods actually check if a file is a file and if it exists (in the case of .is_file()
) and if a directory is a directory and if it exists (in the case of .is_dir()
).
This method is the .exists()
method, which evaluates whether or not the Path object actually points to an existing file or directory.
Let’s see how we can replicate our previous examples using this new method:
# Creating a Path object
from pathlib import Path
file_path = Path('/Users/datagy/Documents/app.py')
directory_path = Path('/Users/datagy/Documents/')
# Using .exists() to check if a file or directory exist
print(file_path.exists())
print(directory_path.exists())
# Returns:
# True
# True
In the next section, you’ll learn how to use the os
module to check if a file or directory exists.
Use Python os to Check if a File Exists
The Python os
module allows us to interact with, well, the operating system itself. As part of this, there are a number of helpful functions included. One of these, path.isfile()
returns a boolean value is a provided path is both a file and the file exists.
The path.isfile()
function takes a single parameter, a string containing a path. It returns a boolean value.
Let’s see how we can use the function to check if a file exists using Python:
# Checking if a file exists with os.path.isfile()
import os
file_path = '/Users/datagy/Documents/app.py'
print(os.path.isfile(file_path))
# Returns: True
The function will return True
if the path points to a file and the file exists. It will return False
if the either the file doesn’t exist or the path doesn’t point to a file.
In the next section, you’ll learn how to use Python to check if a directory exists.
Use Python os to Check if a Directory Exists
Similar to the os.path.isfile()
function, the os
library comes with a function to check if a path points to a directory that exists. This function is the isdir()
function, which takes a path as a parameter. The function returns True
if the directory exists, and False
if the directory doesn’t exist.
Let’s see how this works in Python:
# Checking if a directory exists with os.path.isdir()
import os
file_path = '/Users/datagy/Documents/'
print(os.path.isdir(file_path))
# Returns: True
In the final section, you’ll learn how to check if either a file or a directory exist in Python.
Use Python os to Check if a File or Directory Exists
In this final section, you’ll learn how to use the Python os
module to check if a file or a directory exists. The difference here is that the function is agnostic to file or directory. Furthermore, it allows us to check if a file or directory exists – thereby overwriting the assumption that the function also checks the type of the path.
In this section, we’ll use the os.path.exists()
function to check if a file and a directory exists:
# Checking if a file and directory exist with os.path.exists()
import os
file_path = '/Users/datagy/Documents/app.py'
directory_path = '/Users/datagy/Documents/'
print(os.path.exists(file_path))
print(os.path.exists(directory_path))
# Returns:
# True
# True
Conclusion: Which Approach is Best?
In this tutorial, you learned how to use Python to check if a file or a directory exists. You learned how to use the pathlib
library for an object-oriented approach to accomplish this. You then learned how to use the os
library to check if either a file or a directory exists.
To learn more about the pathlib library, check out the official documentation here. To learn more about the os library, check out the official documentation here.
Additional Resources
To learn about similar topics, check out the articles below: