When you want to open a file and the corresponding file or directory of the given path does not exists, Python raises an Exception. You should address this, otherwise your code will crash.
This article presents different ways how to check if a file or a directory exists in Python, and how to open a file safely.
Use a
try-except block
First of all, instead of checking if the file exists, it’s perfectly fine to directly open it and wrap everything in a
try-except block. This strategy is also known as EAFP (Easier to ask for forgiveness than permission) and is a perfectly accepted Python coding style.
try: f = open("filename.txt") except FileNotFoundError: # doesn’t exist else: # exists
Note: In Python 2 this was an IOError.
Use
os.path.isfile(),
os.path.isdir(), or
os.path.exists()
If you don’t want to raise an Exception, or you don’t even need to open a file and just need to check if it exists, you have different options. The first way is using the different methods in
os.path:
os.path.isfile(path): returns True if the path is a valid file
os.path.isdir(path): returns True if the path is a valid directory
os.path.exists(path): returns True if the path is a valid file or directory
import os if os.path.isfile("filename.txt"): # file exists f = open("filename.txt") if os.path.isdir("data"): # directory exists if os.path.exists(file_path): # file or directory exists
Use
Path.is_file() from
pathlib module
Starting with Python 3.4, you can use the pathlib module. It offers an object-oriented approach to work with filesystem paths, and this is now my preferred way of dealing with files and directories.
You can create a
Path object like this:
from pathlib import Path my_file = Path("/path/to/file")
Now you can use the different methods
is_file(),
is_dir(), and
exists() on the
Path object:
if my_file.is_file(): # file exists if my_file.is_dir(): # directory exists if my_file.exists(): # file or directory exists