How to Check if a File or Directory Exists in Python

When writing Python scripts, you often need to perform an action only when a file or directory exists. For example, you might read or write data to a configuration file, or create a file only if it does not already exist.
Python gives you several ways to check whether a file exists and to determine its type.
This guide explains three different techniques for checking whether a file exists.
Check if File Exists
The simplest way to check whether a file exists is to try to open it. This approach does not require importing any module, so use it when you want to open the file and perform some action.
The following snippet uses a simple try-except block. We are trying to open the file filename.txt, and if the file does not exist, an IOError exception is raised and the “File not accessible” message is printed:
try:
f = open("filename.txt")
# Do something with the file
f.close()
except IOError:
print("File not accessible")You can also catch the more specific FileNotFoundError instead of IOError. In Python 3, IOError is an alias for OSError, and FileNotFoundError is a subclass of it.
When opening files, it is recommended to use the with keyword, which makes sure the file is properly closed after the file operations are completed, even if an exception is raised during the operation. It also makes your code shorter, because you do not need to close the file using the close function.
The following code is equivalent to the previous example:
try:
with open('/etc/hosts') as f:
print(f.readlines())
# Do something with the file
except IOError:
print("File not accessible")In the examples above, we were using the try-except block and opening the file to avoid the race condition. Race conditions happen when you have more than one process accessing the same file.
For example, when you check the existence of a file, another process may create, delete, or block the file in the timeframe between the check and the file opening. This may cause your code to break.
Check if File Exists using the os.path Module
The os.path
module provides some useful functions for working with pathnames and is part of the Python standard library.
In the context of this tutorial, the most important functions are:
os.path.exists(path)- Returns true ifpathrefers to an existing path, including a file or directory. It returns false for broken symlinks.os.path.isfile(path)- Returns true if thepathis a regular file or a symlink to a file.os.path.isdir(path)- Returns true if thepathis a directory or a symlink to a directory.
The following if
statement checks whether the file filename.txt exists:
import os.path
if os.path.isfile('filename.txt'):
print("File exists")
else:
print("File does not exist")Use this method when you need to check whether the file exists before performing an action on the file, for example copying or deleting a file .
If you want to open and modify the file, prefer the previous method.
To check whether a directory exists instead of a regular file, use the os.path.isdir function:
import os.path
if os.path.isdir('/etc'):
print("Directory exists")
else:
print("Directory does not exist")Check if File Exists using the pathlib Module
The pathlib
module is available in Python 3.4 and above. This module provides an object-oriented interface for working with filesystem paths on different operating systems.
As with the previous example, the following code checks whether the file filename.txt exists:
from pathlib import Path
if Path('filename.txt').is_file():
print("File exists")
else:
print("File does not exist")is_file returns true if the path is a regular file or a symlink
to a file. To check whether a directory exists, use the is_dir method:
from pathlib import Path
if Path('/etc').is_dir():
print("Directory exists")
else:
print("Directory does not exist")The main difference between pathlib and os.path is that pathlib allows you to work with the paths as Path objects with relevant methods and attributes, instead of plain str objects.
Conclusion
You now have three reliable ways to check whether a file or directory exists in Python. For most scripts, prefer os.path.isfile() or the pathlib is_file() method, and open the file inside a try-except block when you actually intend to read or write
it.
Tags
Linuxize Weekly Newsletter
A quick weekly roundup of new tutorials, news, and tips.
About the authors

Dejan Panovski
Dejan Panovski is the founder of Linuxize, an RHCSA-certified Linux system administrator and DevOps engineer based in Skopje, Macedonia. Author of 800+ Linux tutorials with 20+ years of experience turning complex Linux tasks into clear, reliable guides.
View author page