Skip to main content

Handling File Errors

When working with files, many things can go wrong:

  • The file does not exist.
  • You do not have permission to read it.
  • The disk is full when writing.

If you do not handle these situations, your program crashes. Let us learn how to make file operations safe.


Catching FileNotFoundError

try:
with open("config.txt", "r") as file:
data = file.read()
print(data)
except FileNotFoundError:
print("Error: config.txt not found! Using default settings.")

Checking If a File Exists Before Opening

Python's os.path module lets you check if a file exists before trying to open it:

import os

file_path = "data.csv"

if os.path.exists(file_path):
with open(file_path, "r") as file:
print(file.read())
else:
print(f"'{file_path}' does not exist.")
Which approach is better?
  • Use try-except when you expect the file to usually exist (EAFP — Easier to Ask Forgiveness than Permission).
  • Use os.path.exists() when you want to check upfront and take a different action.

Handling Permission Errors

try:
with open("/etc/shadow", "r") as file:
print(file.read())
except PermissionError:
print("Error: You do not have permission to read this file.")
except FileNotFoundError:
print("Error: File not found.")

Quick Summary

  • FileNotFoundError: Raised when opening a non-existent file path in read mode.
  • PermissionError: Raised when attempting to access restricted or locked OS files.
  • os.path.exists(path): Pre-checks if a target file exists before attempting to open it.
  • Defensive Practice: Always wrap file operations in structured try-except blocks.

What's Next?

Now let's explore structured tabular datasets and spreadsheets using Python's built-in CSV Basics in the next lesson!