Handling Missing Files
Your program expects a file to exist, but what if it doesn't? Maybe the user deleted it, typed the wrong name, or the file was never created. Without proper handling, your program crashes with an ugly error.
The Problem: FileNotFoundError
When you try to read a file that doesn't exist, Python raises a FileNotFoundError:
with open("missing.txt", "r") as f:
contents = f.read()
FileNotFoundError: [Errno 2] No such file or directory: 'missing.txt'
This stops your program immediately. Users see a confusing error message instead of helpful guidance.
Solution 1: Check Before Reading
Use os.path.exists() to verify the file exists before trying to open it:
import os
filename = "data.txt"
if os.path.exists(filename):
with open(filename, "r") as f:
print(f.read())
else:
print(f"File '{filename}' not found. Please check the path.")
This approach is clear and straightforward. You check first, then act accordingly.
Solution 2: Try/Except
The try/except pattern attempts the operation and catches the error if it occurs:
try:
with open("data.txt", "r") as f:
contents = f.read()
print(contents)
except FileNotFoundError:
print("Sorry, that file doesn't exist.")
This is often preferred because it handles the error exactly where it might occur. It's also slightly more robust — the file could be deleted between your existence check and your read attempt (rare, but possible).
Providing Helpful Messages
Good error messages tell users what went wrong and what to do about it:
import os
filename = "config.json"
try:
with open(filename, "r") as f:
config = f.read()
except FileNotFoundError:
print(f"Configuration file '{filename}' not found.")
print("Please create this file or check the path.")
print(f"Current directory: {os.getcwd()}")
Including the current directory helps users understand where the program is looking.
Handling Multiple Error Types
Files can fail for reasons beyond not existing:
try:
with open("data.txt", "r") as f:
contents = f.read()
except FileNotFoundError:
print("File not found.")
except PermissionError:
print("You don't have permission to read this file.")
except Exception as e:
print(f"Unexpected error: {e}")
PermissionError occurs when the file exists but your program isn't allowed to access it.