Check if a File Exists in Python
When working with files in Python, we often need to check if a file exists before performing any operations like reading or writing. by using some simple methods we can check if a file exists in Python without tackling any error.
Using pathlib.Path.exists (Recommended Method)
Starting with Python 3.4, pathlib module offers a more modern and object-oriented approach to handling file paths. We can use the Path object to check if a file exists.
from pathlib import Path
# File path
a = Path("myfile.txt")
# Check if the file exists
if a.exists():
print("File exists")
else:
print("File does not exist")
Output
File does not exist
There are Other methods that we can use to check if a file exists in python are:
Table of Content
Using os.path.isfile()
If we want to be extra sure that the path is specifically a file (and not a directory) we can use os.path.isfile(). This method works similarly to os.path.exists() but it only returns True if the path is indeed a file and not a directory.
import os
# File path
a = "myfile.txt"
# Check if the file exists and is a file
if os.path.isfile(a):
print("File exists and is a file")
else:
print("File does not exist or is not a file")
Output
File does not exist or is not a file
Using os.path.exists()
The os. path.exists() function is one of the easiest and most efficient ways to check if a file exists in Python. It returns True if the file exists and False if it doesn't.
import os
# File path
a = "myfile.txt"
# Check if the file exists
if os.path.exists(a):
print("File exists")
else:
print("File does not exist")
Output
File does not exist
Note: This method does not differentiate between files and directory.
Using try-except block
If we want to directly attempt to open the file and handle the case where the file does not exist using a try-except block. This method is useful when we want to proceed with reading or writing to the file and catch any errors if it’s not found.
try:
# File path
a = "myfile.txt"
# Try to open the file
with open(a, 'r') as file:
print("File exists and is ready to read")
except FileNotFoundError:
print("File does not exist")
Output
File does not exist
Using os.access (Permission-Specific Check)
This method is suitable when you want to check if file exists, along with checking file-permissions (read, write, execute).
import os
file_path = "myfile.txt"
if os.access(file_path, os.F_OK):
print("File exists")
else:
print("File does not exist")